Home » Php » php – Regex for replacing <p class="someClass"> with <h2> tag?

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

Posted by: admin July 12, 2020 Leave a comment

Questions:

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?

How to&Answers:

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.

Answer:

Do not do it better, but it will help 🙂

$text = '<p class="someClass someOtherClass">content</p>';
$output = str_replace( array('<p', '/p>'), array('<h2', '/h2>'), $text );

Answer:

It will work 🙂

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

Answer:

Sorry, 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, like in a block of text:
Here is how I hardened the regex to cover this situation:

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