str_replace 在某些情况下不起作用 [英] str_replace does not work for some cases

查看:43
本文介绍了str_replace 在某些情况下不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用 curl 获取 html 并将其保存到 $content.然后我尝试了 str_replace,它不起作用:

I use curl to get html and save it to $content. Then I try the str_replace, it doesn't work:

echo str_replace('<a onclick="get_content(\'http://en.wikipedia.org\');" style="cursor: default;">Dojo</a> 应用程序','OK',$content);

但是当我尝试打印 $content 并复制源并将其再次保存到 $content 时,它可以工作:

But when I try to print $content and copy the source and save it to $content again, it works:

echo $content;然后我复制打印并再次将其保存到 $content :

echo $content; Then I copy the printed and save it to $content again:

$content='It is

使用新的 $content,上面的替换有效.

With the new $content, the replacement above works.

推荐答案

这对我有用:

<?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.

这篇关于str_replace 在某些情况下不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆