【问题标题】:PHP Regexp replace: get number of instancesPHP 正则表达式替换:获取实例数
【发布时间】:2013-11-08 08:51:21
【问题描述】:

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

干杯,谢谢!

【问题讨论】:

标签: php regex


【解决方案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>

【讨论】:

    【解决方案2】:

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

    【讨论】:

    • 我知道你是完全正确的,但是我的生产环境,正如 previous question 中所讨论的,挂在 DOM 修改上。我还是不知道为什么:(
    • 这很奇怪,从来没有听说过这样的PHP安装。
    猜你喜欢
    • 2013-12-09
    • 2011-02-21
    • 1970-01-01
    • 1970-01-01
    • 2014-03-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多