在HTML正文中查找<p>元素并插入<span>标记</span> </p>

时间:2015-03-26 10:00:57

标签: preg-replace preg-replace-callback

我有一个HTML文件,例如:

<p class="label" id="p-1'>This is my sample txt </p>
<p class="label" id="p-2'>This is my sample txt </p>
<p class="label" id="p-3'>This is my sample txt </p>
<p class="label" id="p-4'>This is my sample txt </p>
<p class="label" id="p-5'>This is my sample txt </p>

我希望输出看起来像这样:

<p class="label" id="p-1'><span class ="span-class">This is my sample txt </span></p>
<p class="label" id="p-2'><span class ="span-class">This is my sample txt </span></p>
<p class="label" id="p-3'><span class ="span-class">This is my sample txt </span></p>
<p class="label" id="p-4'><span class ="span-class">This is my sample txt </span></p>
<p class="label" id="p-5'><span class ="span-class">This is my sample txt </span></p>

这是否可以使用preg_replace?有没有其他方法可以实现这个目标?

1 个答案:

答案 0 :(得分:0)

在php中,您可以通过以下方式实现此目的:

<?php

$html = <<< LOB
<p class="label" id="p-1'>This is my sample txt </p>
<p class="label" id="p-2'>This is my sample txt </p>
<p class="label" id="p-3'>This is my sample txt </p>
<p class="label" id="p-4'>This is my sample txt </p>
<p class="label" id="p-5'>This is my sample txt </p>
LOB;

echo preg_replace('%<p class="label" id="p-(.*?)\'>(.*?)</p>%sim', '<p class="label" id="p-$1\'><span class ="span-class">$2</span></p>', $html);

?>

<强>说明

<p class="label" id="p-(.*?)'>(.*?)</p>

Options: Case insensitive; Exact spacing; Dot matches line breaks; ^$ match at line breaks; Greedy quantifiers; Regex syntax only

Match the character string “<p class="label" id="p-” literally (case insensitive) «<p class="label" id="p-»
Match the regex below and capture its match into backreference number 1 «(.*?)»
   Match any single character «.*?»
      Between zero and unlimited times, as few times as possible, expanding as needed (lazy) «*?»
Match the character string “'>” literally «'>»
Match the regex below and capture its match into backreference number 2 «(.*?)»
   Match any single character «.*?»
      Between zero and unlimited times, as few times as possible, expanding as needed (lazy) «*?»
Match the character string “</p>” literally (case insensitive) «</p>»

<p class="label" id="p-$1'><span class ="span-class">$2</span></p>

Insert the character string “<p class="label" id="p-” literally «<p class="label" id="p-»
Insert the text that was last matched by capturing group number 1 «$1»
Insert the character string “'><span class ="span-class">” literally «'><span class ="span-class">»
Insert the text that was last matched by capturing group number 2 «$2»
Insert the character string “</span></p>” literally «</span></p>»

DEMO: http://ideone.com/YaZG2p