qwerty qwerty - 3 months ago 9
PHP Question

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

I need to replace all:

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


with

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


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

This is what i have so far:

/<p(.*?)class="(.*?)pageTitle(.*?)">(.*?)<\/p>/


That matches the entire
<p>
tag, but i'm not sure how i would go about replacing the
<p>
with
<h2>


How would i go about doing this?

Answer

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.