tags:

views:

73

answers:

4

Variable $name (string) gives something like (5 possible values):

"Elton John"
"Barak Obama"
"George Bush"
"Julia"
"Marry III Great"

Want to add <br /> after the first whitespace (" " between words).

So, it should give when echo:

"Elton<br/>John"
"Barak<br/>Obama"
"George<br/>Bush"
"Julia"
"Marry<br/>III Great"

1) <br /> should be added only if there is more than one word in a string.

2) Only after the first word.

3) Can be more than 3 words in variable.

Thanks.

A: 
if (($pos = strpos($name, " ")) !== false) {
    $name = substr($name, 0, $pos + 1) . "<br />" . substr($name, $pos +1);

}
Artefacto
Doesn't account for "1) <br /> should be added only if there is more than one word in a string" and "2) Only after the first word."
no
@no Yes it does. Well, to be exact, it will add <br /> if there's only one word, but there's a space somwehere. Other than that, it's fine.
Artefacto
With your solution, " bob" becomes " <br />bob" ... as far as I can tell that goes against both 1 and 2.
no
@no Yes, it will fail if there are spaces before the first word or after the only word. If working under these circumstances is necessary, look somewhere else or call `trim` before.
Artefacto
We should assume there's some weird formatting going on in some of those strings because of the OP's rules "1" and "2." Calling `trim` will make further changes to the string that weren't part of the OP's requirements. Usually if you need to do text processing where several rules apply, regex is the way to go. If requirements change, the regex can be changed instead of changing several lines of code or adding more conditions or whatever. Just a thought.
no
A: 
if (count(explode(' ', trim($string))) > 1) {
   str_replace(' ', ' <br />', $string);
}
blcArmadillo
A: 
$name = preg_replace('/([^ ]+) ([^ ]+)/', '\1 <br />\2', $name, 1);

Testing it out...

$names=array(" joe ", 
             "big billy bob", 
             " martha stewart ", 
             "pete ", 
             " jim", 
             "hi mom");

foreach ($names as $n) 
  echo "\n". preg_replace('/([^ ]+) ([^ ]+)/', '\1 <br />\2', $n, 1);

..gives...

 joe 
big <br />billy bob
 martha <br />stewart 
pete 
 jim
hi <br />mom
no
A: 

This implements all your requirements:

$tmp = explode(' ', trim($name));

if (count($tmp) > 1)
  $tmp[0] = $tmp[0] . '<br />';

$name = trim(implode($tmp, ' '));
Johan