6

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

4 に答える 4

13

以下はあなたが望むことをするはずです:

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

dot(.)はすべてに一致します。アスタリスクは、0または任意の数の一致に一致します。括弧内はすべてグループです。$2変数は、一致したグループへの参照です。中括弧({1})内の数字は数量詞です。これは、前のグループに1回一致することを意味します。その数量詞はおそらく必要ありませんが、とにかくそこにあり、正常に機能します。バックスラッシュは特殊文字をエスケープします。最後に、疑問符は.*ビットを貪欲ではなくします。デフォルトでは貪欲ではないからです。

于 2012-11-08T08:40:23.300 に答える
1

もっとうまくやらないでください、しかしそれは助けになります:)

$text = '<p class="someClass someOtherClass">content</p>';
$output = str_replace( array('<p', '/p>'), array('<h2', '/h2>'), $text );
于 2012-11-08T08:28:09.440 に答える
0

それが動作します :)

preg_replace('/<p .*?class="(.*?)">(.*?)<\/p>/','<h2 class="$1">$2</h2>',$value);
于 2013-06-13T12:33:12.343 に答える