douluan5738 2014-04-27 16:25
浏览 26
已采纳

未定义的偏移量错误(PHP / Regex)

The script below assigns numerical ID's to paragraphs (e.g. [p id="1"]) in articles extracted from my database, except for the last paragraph, which is [p id="last].

$c = 1;
$r = preg_replace_callback('/(<p( [^>]+)?>)/i', function ($res) {
 global $c;
 return '<p'.$res[2].' id="'.intval($c++).'">';
}, $text);
$r = preg_replace('/(<p.*?)id="'.($c-1).'"(>)/i', '\1id="Last"\2', $r);
$text = $r;

It works, but when I have my error reporting on, I get the following error Undefined offset: 2. It isn't critical, but it's kind of a nuisance when I'm testing my pages. Any idea how I can kill it?

  • 写回答

1条回答 默认 最新

  • drrqwokuz71031449 2014-04-27 17:52
    关注

    I've improved the regex by:

    • Removing a group /<p( [^>]+)?>/i
    • Changing ( [^>]+)? to ([^>]*). This way you don't have an optional group, but the characters inside this group is optional. Which means you will always have this group.
    • Just a preference, I change the delimiters ~<p([^>]*)>~i

    Now let's attack the php code:

    $text = '<p>test</p> another <p class="test">test</p> and another one <p style="color:red">';
    $c = 1;
    $r = preg_replace_callback('~<p([^>]*)>~i', function($res) use (&$c){
        return '<p'.$res[1].' id="'.$c++.'">';
    }, $text);
    
    var_dump($r, $c);
    

    Note that I used a closure use (&$c) with a reference &. This way we can update $c.

    <kbd>Online demo</kbd>

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 ikuai客户端多拨vpn,重启总是有个别重拨不上
  • ¥20 关于#anlogic#sdram#的问题,如何解决?(关键词-performance)
  • ¥15 相敏解调 matlab
  • ¥15 求lingo代码和思路
  • ¥15 公交车和无人机协同运输
  • ¥15 stm32代码移植没反应
  • ¥15 matlab基于pde算法图像修复,为什么只能对示例图像有效
  • ¥100 连续两帧图像高速减法
  • ¥15 如何绘制动力学系统的相图
  • ¥15 对接wps接口实现获取元数据