Miss Phuong
Miss Phuong

Reputation: 289

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?

Upvotes: 0

Views: 1649

Answers (3)

user428517
user428517

Reputation: 4193

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.

Upvotes: -2

GolezTrol
GolezTrol

Reputation: 116140

$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

Upvotes: 3

SomeKittens
SomeKittens

Reputation: 39522

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

Upvotes: 0

Related Questions