简体   繁体   中英

str_replace to remove a paragraph PHP

I have a php file with:

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

It works for for search and replace or remove a string. But If old string is a paragraph, example:

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

How to remove that table in content?

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

Note that if you want to replace such a piece of HTML, you must make sure you don't include extra whitespace in the string. str_replace makes an exact match and will fail otherwise.

The alternatives are

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

You can use preg_replace() . The high likelihood of str_replace() failing if/when you mistype something is why I wouldn't use it, but if you know exactly what you want to match and can type it precisely, it's the better option.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM