且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

str_replace 在某些情况下不起作用

更新时间:2022-04-16 22:33:36

这对我有用:

<?php
$content='it is <a onclick="get_content(\'http://en.wikipedia.org\');" style="cursor: default;">Dojo</a> Applications';
echo str_replace('<a onclick="get_content(\'http://en.wikipedia.org\');" style="cursor: default;">Dojo</a> Applications','OK',$content); 

所以你可能在字符串中有实际的换行符,它们没有以相同的格式编码,例如,一个是 \n (Linux),另一个是 \r\n (Windows).您可以在比较之前对两个字符串进行标准化:

So you probably have actual line feeds inside the strings and they aren't encoded in the same format, e.g., one is \n (Linux) and the other is \r\n (Windows). You can normalize both strings before comparing:

<?php
$content = strtr($content, array(
    "\r\n" => PHP_EOL,
    "\r" => PHP_EOL,
    "\n" => PHP_EOL,
));

无论如何,PHP 具有出色的函数来处理 HTML.我不建议在任务中使用正则表达式:它们不可靠并且很难几乎正确.

In any case, PHP has excellent functions to handle HTML. I would not recommend regular expressions for the task: they're unreliable and very hard to get almost right.