将段落替换为标题时,无法使str_replace()函数正常工作

时间:2012-10-07 09:56:31

标签: php

我有一个像这样的正常段落:

<p>Hey there, I'm a normal paragraph. generated by a Wordpress blog</p>

我想改变:

<p> with <h2> and </p> with </h2>

我使用了str_replace();

$paragraph = array("<p>", "</p>");
$heading2 = array("<h2>","</h2>");
$first_sentence = str_replace($paragraph, $heading2, $first_sentence);

它应该有效,但我明白了:

<h2>Hey there, I'm a normal paragraph. generated by a Wordpress blog<p>/p&gt;</p>

任何想法为什么?

1 个答案:

答案 0 :(得分:0)

您可以使用Regex执行此类任务:

$first_sentence = preg_replace('/<p>([^<]+)<\/p>/', '<h2>$1</h2>', $first_sentence);

([^<]+)表示:捕捉所有字符,直到<出现。

在这里你可以看到它有效:http://codepad.viper-7.com/FW1vm5

但如果它变得更复杂,你应该使用其他技术(如DOM解析器)