Regex for replacing

with

2019-03-27 14:52发布

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?

4条回答
虎瘦雄心在
2楼-- · 2019-03-27 15:26

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.

查看更多
戒情不戒烟
3楼-- · 2019-03-27 15:30

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 );
查看更多
霸刀☆藐视天下
4楼-- · 2019-03-27 15:33

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);
查看更多
Fickle 薄情
5楼-- · 2019-03-27 15:36

It will work :)

preg_replace('/<p .*?class="(.*?)">(.*?)<\/p>/','<h2 class="$1">$2</h2>',$value);
查看更多
登录 后发表回答