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.
$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
if (($pos = strpos($name, " ")) !== false) {
$name = substr($name, 0, $pos + 1) . "<br />" . substr($name, $pos +1);
}
This implements all your requirements:
$tmp = explode(' ', trim($name));
if (count($tmp) > 1)
$tmp[0] = $tmp[0] . '<br />';
$name = trim(implode($tmp, ' '));
if (count(explode(' ', trim($string))) > 1) {
str_replace(' ', ' <br />', $string);
}
精彩评论