0

有没有办法使用 替换模式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);

where\\?将被转换为 0 和 1,因此输出将是

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

干杯和感谢!

4

2 回答 2

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>
于 2013-11-08T09:23:50.630 回答
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>
于 2013-11-08T09:05:48.843 回答