0

我有一个 php 文件:

$content = str_replace('search old string','by new string',$content);
$content = str_replace('search old string','by new string',$content);

它适用于搜索和替换或删除字符串。但是如果旧字符串是一个段落,例如:

<table class="adverting_I_want_to_remove">
  <tr>
    <td>Dynamic Advertise content 1</td>
    <td>Dynamic Advertise content 2</td>
  </tr>
</table>

如何在内容中删除该表?

4

3 回答 3

3
$content = str_replace('<table>
  <tr>
    <td>TD 1</td>
    <td>TD 2</td>
  </tr>
</table>','by new string',$content);

请注意,如果您想替换这样一段 HTML,您必须确保不要在字符串中包含额外的空格。str_replace 进行完全匹配,否则将失败。

替代方案是

于 2012-10-18T19:33:10.467 回答
0

First off, don't use regular expressions. Your best bet to edit HTML would be to use the DOMDocument class to parse through it.

于 2012-10-18T19:39:03.037 回答
-2

您可以使用preg_replace(). 如果/当您输错某些内容时,失败的可能性很高,str_replace()这就是我不使用它的原因,但是如果您确切知道要匹配的内容并且可以精确输入,那么它是更好的选择。

preg_replace('/<table>.*<\/table>/s', '', $content);

If you don't know how to use regular expressions, look them up and learn 'em. You can be more or less specific about what you want to replace by adjusting the regex.

于 2012-10-18T19:35:24.667 回答