Regex to replace <p class = "someClass"> with the <h2> tag?
I need to replace everything:
<p class="someClass someOtherClass">content</p> from
<h2 class="someClass someOtherClass">content</h2> in the content bar. Basically I just want to replace "p" with "h2" .
This is what I still have:
/<p(.*?)class="(.*?)pageTitle(.*?)">(.*?)<\/p>/ This matches the entire <p> , but I'm not sure how I would like to replace <p> with <h2>
How can i do 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. An asterisk matches either 0 or the number of matches. All that is inside the parenthesis is a group. The variable $2 is a reference to a consistent group. The number inside braces ( {1} ) is a quantifier, which means a match with the previous group once. This quantifier is probably not needed, but it is there anyway and works fine. The backslash avoids any special characters. Finally, the question mark makes the bit .* Non-living, since it is by default.
Sorry, a little late to the party. I used the regex from the answer:
$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; this approach has a problem when you have more p-tags, for example, in a block of text: Here is how I hardened the regular expression to cover this situation:
$newstr = preg_replace('/<p [^<]*?class="([^<]*?someClass.*?)">(.*?)<\/p>/','<h2 class="$1">$2</h2>',$str);