【问题标题】:str_replace() with a full web page as the subjectstr_replace() 以完整网页为主题
【发布时间】:2016-02-13 02:05:28
【问题描述】:

我正在尝试使用str_replace() 来搜索和替换 html 页面中的特定字符串。例如,我正在替换:

$search_string = 'The new&nbsp;funding follows a <a href="http://blog.classpass.com/2015/01/15/were-so-excited-to-share-our-biggest-news-ever/">$40 million raise announced</a> in January.';

$replacement = '<span class="newString">The new&nbsp;funding follows a <a href="http://blog.classpass.com/2015/01/15/were-so-excited-to-share-our-biggest-news-ever/">$40 million raise announced</a> in January.</span>';

$subject = file_get_contents("some-web-site.html");

$new_string = str_replace($search_string, $replacement, $subject);

但是,当$subject 包含大量html 时,替换不起作用。如果我只是这样做:

$subject = "some text some text " .  $search_string . "some text some text";

句子被正确替换。这个问题似乎特别是由于&amp;nbsp; 元素而出现的。如果$search_string 不包含&amp;nbsp;,那么无论$subject 元素的复杂性如何(即即使它包含完整的网页)。

知道为什么吗?

【问题讨论】:

  • 您使用的是preg_replace 还是str_replace?你提到两者。用"&amp;nbsp;" 之类的东西做str_replace 似乎对我来说效果很好。 preg_replace 可能会失败,因为它遇到了未转义的元字符,例如&amp;.
  • 对不起,我到处都在使用 str_replace。但是如果可以解决问题,我会使用 preg_replace

标签: php html replace str-replace


【解决方案1】:

这似乎是$search_string$40 部分的问题,而不是&amp;nbsp;

以这个程序为例:

<?php

$input = '$40 &nbsp; replace failed'; // string literal

$str_replace_result = str_replace('$40 &nbsp; replace failed', 'str_replace worked', $input);
print_r($str_replace_result . "\n"); // ==> works

$preg_replace_result = preg_replace('/$40 &nbsp; replaced failed/', 'preg_replace worked', $input);
print_r($preg_replace_result . "\n"); // ==> fails

// Example without the "$40"
$another_string = '&nbsp; replace 2 failed';
$preg_replace_result2= preg_replace('/&nbsp; replace 2 failed/', 'preg_replace worked', $another_string);
print_r($preg_replace_result2. "\n"); // ==> works, implying the "$40" bit was the issue

要解决此问题,请使用preg_quote,例如:

// Solution
$escaped_search = preg_quote('/$40 &nbsp; replace failed/');
$newnewstr = preg_replace($escaped_search, 'preg_replace worked', $input);
print_r($newnewstr . "\n"); // ==> works

this question 中的更多信息。

总之,问题在于未转义的元字符导致匹配失败。

说了这么多,是否需要您以这种方式替换整个网页?这种方法(在这里很明显)似乎容易出错。

【讨论】:

  • 谢谢,但我认为这与美元符号无关。如果我创建一个小的 $subject = "some text"。 $search_string/*(这包含 $40)*/ 。 “ahoer text”)它有效
  • 我只需要替换网页中的那个字符串,而不是整个页面
  • @user3857924 好的。我能想到的唯一另一件事是使用智能字符串 (") 与字符串文字 ('),由于模式匹配的性质,您希望在此处使用后者(这仍然与 @987654331 有关@ 问题)。除此之外,如果preg_quote 不能解决您的问题,我不确定,至少根据给定的信息。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-05-15
  • 1970-01-01
  • 1970-01-01
  • 2012-01-06
  • 2012-06-22
  • 2012-05-13
相关资源
最近更新 更多