awm
awm

Reputation: 1200

how to use preg_replace to remove all following style tag/pattern occurrences in a string?

I am trying to find a regex to match the following:

<style type="text/css"> .article-content{ position: relative;

padding-bottom: 140px;} .pane.pane-newsletter-contextual{ display: block;

bottom: 32px; position: absolute; left: 0px; margin-left: 0px; } </style>

I need the regex in order to pass it to preg_replace and remove it from a string. I have basic knowledge of regex and tried this after reviewing the basic on http://www.regular-expressions.info/examples.html

preg_replace("/<style\b[^>]*>(.*?)</style>/", "", $body);

However this line is giving the following error Unknown modifier 't' in ...

Also, I tried searching before positing the question and could not find any that is similar.

Upvotes: 3

Views: 11929

Answers (1)

shinkou
shinkou

Reputation: 5154

You forgot to escape the slash...

preg_replace("/<style\\b[^>]*>(.*?)<\\/style>/s", "", $body);

More info about the modifiers here.

As of why we need 2 backslashes, because we need a backslash character in the string to escape the slash. And unfortunately, in PHP, we need a double backslash \\ to represent a single backslash character in all single or double quoted strings. It is not a must, but when things get complicated, it helps make things clearer.

Alternatively, you could choose a different character as the identifier. For example,

preg_replace("|<style\b[^>]*>(.*?)</style>|s", "", $body);

This way, you could avoid escaping the slashes.

EDIT: Added modifier to make the replacement "work".

EDIT2: Added explanation of the double backslash in the pattern string.

EDIT3: Added an alternative.

Upvotes: 10

Related Questions