Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 226
qwerty Avatar asked Nov 08 '12 08:11

qwerty


2 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.

like image 189
Daedalus Avatar answered Sep 18 '22 22:09

Daedalus


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 );
like image 37
Konstantin Avatar answered Sep 21 '22 22:09

Konstantin