PHP正则表达式替换:获取实例数

时间:2013-11-08 08:51:22

标签: php regex

有没有办法用preg_replace替换模式,并替换出现的索引

例如,在像

这样的字符串中
<p class='first'>hello world</p>
<p class='second'>this is a string</p>

我想用

preg_replace("/<p\s?(.*?)>(.*?)<\/pp>/ms", "<pre \\1 id='myid\\?'>\\2</pre>", $obj);

其中\\?将转换为0和1,因此输出将为

<pre class='first' id='myid0'>hello world</pre>
<pre class='second' id='myid1'>this is a string</pre>

干杯&amp;谢谢!

2 个答案:

答案 0 :(得分:1)

如果你必须走这条路,请使用preg_replace_callback()

$html = <<<DATA
<p class='first'>hello world</p>
<p class='second'>this is a string</p>
<p class='third'>this is another string</p>
DATA;

$html = preg_replace_callback('~<p\s*([^>]*)>([^>]*)</p>~', 
      function($m) { 
         static $id = 0;                                
         return "<pre $m[1] id='myid" . $id++ . "'>$m[2]</pre>"; 
      }, $html);

echo $html;

输出

<pre class='first' id='myid0'>hello world</pre>
<pre class='second' id='myid1'>this is a string</pre>
<pre class='third' id='myid2'>this is another string</pre>

答案 1 :(得分:0)

我建议转储正则表达式路由并使用更安全和正确的方法来执行此操作,即DOM解析器。请考虑以下代码:

$html = <<< EOF
<p class='first'>hello world</p>
<p class='second'>this is a string</p>
EOF;
$doc = new DOMDocument();
libxml_use_internal_errors(true);
$doc->loadHTML($html); // loads your html
$xpath = new DOMXPath($doc);
// find all the <p> nodes
$nodelist = $xpath->query("//p");
// loop through <p> notes
for($i=0; $i < $nodelist->length; $i++) {
    $node = $nodelist->item($i);
    // set id attribute
    $node->setAttribute('id', 'myid'.$i);
}
// save your modified HTML into a string
$html = $doc->saveHTML();
echo $html;

<强>输出:

<html><body>
<p class="first" id="myid0">hello world</p>
<p class="second" id="myid1">this is a string</p>
</body></html>