开发者

Add <br> when echo

开发者 https://www.devze.com 2023-01-09 19:53 出处:网络
Variable $name (string) gives something like (5 possible values): 开发者_高级运维\"Elton John\"

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);
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号