用于替换< p class ="someClass">的正则表达式.与< h2>标签? [英] Regex for replacing <p class="someClass"> with <h2> tag?

查看:142
本文介绍了用于替换< p class ="someClass">的正则表达式.与< h2>标签?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要替换所有内容

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

使用

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

在内容字符串中.基本上我只想用"h2"替换"p".

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>/

与整个<p>标签匹配,但是我不确定如何将<p>替换为<h2>

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

我将如何去做?

推荐答案

以下应做您想做的事情:

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;

点(.)匹配所有.星号匹配0或任意多个匹配项.括号内的任何东西都是一个组. $2变量是对匹配组的引用.大括号({1})中的数字是一个量词,表示一次匹配上一个组.可能不需要该量词,但无论如何它都可以正常工作.反斜杠转义任何特殊字符.最后,问号使.*位为非贪婪的,因为默认情况下为.

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.

这篇关于用于替换&lt; p class ="someClass"&gt;的正则表达式.与&lt; h2&gt;标签?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆