Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialAbe Layee
8,378 PointsChanging spaces within a string to specific character
I am trying to replace the spaces within the string to something like this "Keep*your--spacing-perfect!". Replace one space with an asterisk and two spaces with -. This is what I have so far.
<?php
$subject = "Keep your spacing perfect!";
while(strpos($subject,' ') !== false) {
$subject = str_replace(' ','*',$subject);
}
echo $subject;
// the output of this code is this
//Keep*your**spacing**perfect!";
// my goal is this
//Keep*your--spacing-*perfect!";
?>
1 Answer
Antonio De Rose
20,885 Points<?php
var_dump(preg_replace('/([^\s]+)(\s)([^\s]+)/', '$1*$3', preg_replace('/([^\s]+)(\s\s)([^\s]+)/', '$1-$3', 'Keep your spacing perfect!')));
?>