使用

标签替换

的正则表达式?

[英]Regex for replacing

with

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

在一串内容中。基本上我只想用“h2”替换“p”。

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 个解决方案

#1


11  

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.

点(。)匹配所有。星号匹配0或任意数量的匹配。括号内的任何内容都是一个组。 $ 2变量是对匹配组的引用。大括号({1})内的数字是一个量词,表示匹配前一个组一次。这个量词可能不是必需的,但无论如何它仍然存在并且工作正常。反斜杠会转义任何特殊字符。最后,问号使得。*位非贪婪,因为默认情况下它是。

#2


1  

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 );

#3


0  

It will work :)

它会工作:)

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

#4


0  

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:

当你有更多的p标签时,这种方法有一个问题,就像在一个文本块中:这是我如何硬化正则表达式来覆盖这种情况:

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

注意!

本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:http://www.itdaan.com/blog/2012/11/08/8fadb47c6518ab20f1300cd964082298.html



 
© 2014-2018 ITdaan.com 粤ICP备14056181号