带有多个令牌替换的PHP preg_replace

时间:2014-05-23 02:05:49

标签: php regex preg-replace

我在PHP函数中有以下字符串($ line)。

$line='<span class="cooktime">25 Mins<span class="value-title" title="PT0H25M"></span></span><span class="preptime">30 Mins<span class="value-title" title="PT0H30M"></span></span>';

我想使用preg_replace或任何其他方法将每个跨度集转换为以下内容:

$line='<span class="cooktime">25 Mins<span class="value-title" itemprop="cookTime" content="PT0H25M"></span></span><span class="preptime">30 Mins<span class="value-title" itemprop="prepTime" title="PT0H30M"></span></span>';

基本上我将itemprop属性添加到span块并将title属性重命名为content。

我如何实现这一目标?

感谢您的时间,JK

3 个答案:

答案 0 :(得分:0)

可以尝试这样的事吗? (没有在PHP中测试,但是使用JavaScript测试了RegEx,它似乎有用。)

preg_replace("^(.+)title(.+)$","$1itemprop=\"prepTime\" content$2",$line);

答案 1 :(得分:0)

尝试使用:

$str = '<span class="cooktime">25 Mins<span class="value-title" title="PT0H25M"></span></span>';
$str = preg_replace('/" title="/', '" itemprop="prepTime" content="', $str);
echo $str,"\n";

<强>输出:

<span class="cooktime">25 Mins<span class="value-title" itemprop="prepTime" content="PT0H25M"></span></span>

答案 2 :(得分:0)

好的 - 我找到了答案。感谢Andrew&amp; M42给出了想法。这是:

$line = preg_replace('/\ (.*?)class="preptime"(.*?)<span class="value-title" title(.*?)/i','$1class="preptime"$2<span class="value-title" itemprop="prepTime" content$3',$line);
$line = preg_replace('/\ (.*?)class="cooktime"(.*?)<span class="value-title" title(.*?)/i','$1class="cooktime"$2<span class="value-title" itemprop="cookTime" content$3',$line);