qwerty qwerty - 1 month ago 6x
PHP Question

Regex for replacing <p class="someClass"> with <h2> tag?

I need to replace all:

<p class="someClass someOtherClass">content</p>


<h2 class="someClass someOtherClass">content</h2>

in a string of content. Basically i just want to replace the
with a

This is what i have so far:


That matches the entire
tag, but i'm not sure how i would go about replacing the

How would i go about doing this?


The following should do what you want:

$str = '<p>test</p><p class="someClass someOtherClass">content</p>';

$newstr = preg_replace('/<p .*?class="(.*?someClass.*?)">(.*?)<\/p>/','<h2 class="$1">$2</h2>',$str);

echo $newstr;

The dot(.) matches all. The asterisk matches either 0 or any number of matches. Anything inside the parenthesis is a group. The $2 variable is a reference to the matched group. The number inside the curly brackets({1}) is a quantifier, which means match the prior group one time. That quantifier likely isn't needed, but it's there anyway and works fine. The backslash escapes any special characters. Lastly, the question mark makes the .* bit be non-greedy, since by default it is.