当回声时添加<br/>

时间:2010-07-30 15:38:35

标签: php regex

变量$name(字符串)给出类似(5个可能的值)的内容:

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

想要在第一个空格之后添加<br />(单词之间的“”)。

所以,它应该在echo时给出:

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

1)只有在字符串中有多个单词时才应添加<br />

2)仅在第一个单词之后。

3)变量可以超过3个单词。

4 个答案:

答案 0 :(得分:0)

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

}

答案 1 :(得分:0)

if (count(explode(' ', trim($string))) > 1) {
   str_replace(' ', ' <br />', $string);
}

答案 2 :(得分:0)

$name = preg_replace('/([^ ]+) ([^ ]+)/', '\1 <br />\2', $name, 1);

测试出来......

$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);

..给出...

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

答案 3 :(得分:0)

这可以满足您的所有要求:

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

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

$name = trim(implode($tmp, ' '));
相关问题