php中的str_replace

时间:2010-02-21 19:58:08

标签: php str-replace

我有一个长字符串,可以同时保存所有这些值:

hello<!>how are you? <!>I am fine<!> What is up? <!> Nothing!

我需要找到所有这些可能性:

' <!> '
' <!>'
'<!> '
'<!>'

并用“\ n”替换它们

可以用php中的str_replace实现吗?

7 个答案:

答案 0 :(得分:6)

如果您只有这4种可能性,那么您可以使用str_replace

$str = str_replace( array( ' <!> ', ' <!>', '<!> ', '<!>' ), "\n", $str );
  

是的,但如果有两个空格怎么办?还是标签?你为每个人添加一个空间案例吗?

您可以为每个案例添加特殊案例,也可以使用正则表达式:

$str = preg_replace( '/\s*<!>\s*/', "\n", $str );

答案 1 :(得分:4)

当然,您可以通过4次调用str_replace来实现此目的。 编辑:我错了。您可以在str_replace中使用数组。

$str = str_replace(' <!> ', "\n", $str);
$str = str_replace(' <!>',  "\n", $str);
$str = str_replace('<!> ',  "\n", $str);
$str = str_replace('<!>',   "\n", $str);

还可以考虑使用strtr,这样就可以一步完成。

$str = strtr($str, array(
    ' <!> ' => "\n",
    ' <!>'  => "\n",
    '<!> '  => "\n",
    '<!>'   => "\n"
));

或者您可以使用regular expression

$str = preg_replace('/ ?<!> ?/', "\n", $str);

答案 2 :(得分:1)

你当然可以用str_replace这样做:

$needles = array(" <!> ","<!> "," <!>","<!>");
$result = str_replace($needles,"\n",$text);

答案 3 :(得分:0)

修改:preg_replace('/\s*<!>\s*', PHP_EOL, $string);应该更好。

当然,str_replace('<!>', "\n", $string);如果你的例子已经完成。

答案 4 :(得分:0)

只有str_replace才能做到这一点。使用explodestripimplode或用户preg_replace的组合。

答案 5 :(得分:0)

您可以使用:

//get lines in array
$lines = explode("<!>", $string);
//remove each lines' whitesapce
for(i=0; $i<sizeof($lines); $i++){
    trim($lines[$i]);
}
//put it into one string
$string = implode("\n", $lines)

这有点单调乏味,但这应该有效(同时删除两个空格和标签)。 (没有测试代码,因此可能存在错误)

答案 6 :(得分:0)

这有点整洁:

$array = explode('<!>', $inputstring);
foreach($array as &$stringpart) {
  $stringpart = trim($stringpart);
}
$outputstring = implode("\r\n", $array);