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


PHP Regexp replace: get number of instances

有没有办法使用 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>

干杯和谢谢!

如果您必须走这条路,请使用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>

我建议转储正则表达式路由并使用更安全和适当的方法来执行此操作,即 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>