【发布时间】:2010-02-21 19:58:08
【问题描述】:
我有一个可以同时保存所有这些值的长字符串:
hello<!>how are you? <!>I am fine<!> What is up? <!> Nothing!
我需要找到所有这些可能性:
' <!> '
' <!>'
'<!> '
'<!>'
并将它们替换为“\n”
用php中的str_replace可以实现吗?
【问题讨论】:
标签: php str-replace
我有一个可以同时保存所有这些值的长字符串:
hello<!>how are you? <!>I am fine<!> What is up? <!> Nothing!
我需要找到所有这些可能性:
' <!> '
' <!>'
'<!> '
'<!>'
并将它们替换为“\n”
用php中的str_replace可以实现吗?
【问题讨论】:
标签: php str-replace
如果您只有这 4 种可能性,是的,那么您可以通过 str_replace 做到这一点。
$str = str_replace( array( ' <!> ', ' <!>', '<!> ', '<!>' ), "\n", $str );
是的,但是如果有两个空格呢?还是标签?您是否为每个添加了空间案例?
您可以为每种情况添加特殊情况,或使用正则表达式:
$str = preg_replace( '/\s*<!>\s*/', "\n", $str );
【讨论】:
当然,您可以通过 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);
【讨论】:
你当然可以像这样用 str_replace 做到这一点:
$needles = array(" <!> ","<!> "," <!>","<!>");
$result = str_replace($needles,"\n",$text);
【讨论】:
您不能仅使用str_replace 来做到这一点。使用explode、strip 和implode 的组合,或者使用用户preg_replace。
【讨论】:
编辑:preg_replace('/\s*<!>\s*', PHP_EOL, $string); 应该更好。
当然,如果您的示例完整,str_replace('<!>', "\n", $string);。
【讨论】:
你可以使用:
//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)
这有点乏味,但这应该可以工作(还删除了两个空格和制表符)。 (没有测试代码,所以可能有错误)
【讨论】:
这有点整洁:
$array = explode('<!>', $inputstring);
foreach($array as &$stringpart) {
$stringpart = trim($stringpart);
}
$outputstring = implode("\r\n", $array);
【讨论】: