Irene T.
Irene T.

Reputation: 1393

Remove a div by id with preg_replace

hello i have an html string with output

$incoming_data = '<div id=\"title\">a title</div>';

And i want to remove it with preg_replace

i tried the code bellow without any luck..

result = preg_replace('#<div id="title">(.*?)</div>#', ' ', $incoming_data);

Any ideas?

Upvotes: 0

Views: 3683

Answers (1)

The fourth bird
The fourth bird

Reputation: 163362

The variable $incoming_data contains escaped quotes, so you have to escape the backslash for the php regex pattern to match it.

Then your updated code would be:

$incoming_data = '<div id=\"title\">a title</div>';
$result = preg_replace('#<div id=\\\"title\\\">(.*?)</div>#', ' ', $incoming_data);

If you first want to strip the slashes from the string, you can use the stripslashes function.

Then your updated code would be:

$incoming_data = stripslashes('<div id=\"title\">a title</div>');
$result = preg_replace('#<div id="title">(.*?)</div>#', ' ', $incoming_data);

For the dom traversal you can use the DOMDocument class.

Upvotes: 2

Related Questions