1

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

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

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

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

并将它们替换为“\n”

可以用 php 中的 str_replace 来实现吗?

4

7 回答 7

6

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

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

是的,但是如果有两个空格呢?还是标签?您是否为每个添加了一个空间案例?

您可以为每种情况添加特殊情况,或使用正则表达式:

$str = preg_replace( '/\s*<!>\s*/', "\n", $str );
于 2010-02-21T20:08:04.340 回答
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"
));

或者您可以使用正则表达式

$str = preg_replace('/ ?<!> ?/', "\n", $str);
于 2010-02-21T20:02:04.870 回答
1

你当然可以像这样使用 str_replace 来做到这一点:

$needles = array(" <!> ","<!> "," <!>","<!>");
$result = str_replace($needles,"\n",$text);
于 2010-02-21T20:02:09.967 回答
0

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

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

于 2010-02-21T20:00:17.403 回答
0

你不能只用str_replace. 使用explode,stripimplode, 或 user的组合preg_replace

于 2010-02-21T20:03:16.173 回答
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)

这有点乏味,但这应该可以工作(也删除了两个空格和制表符)。(没有测试代码,所以可能有错误)

于 2010-02-21T20:10:43.137 回答
0

这有点整洁:

$array = explode('<!>', $inputstring);
foreach($array as &$stringpart) {
  $stringpart = trim($stringpart);
}
$outputstring = implode("\r\n", $array);
于 2010-02-21T20:14:04.930 回答