下面的脚本将数字ID分配给从我的数据库中提取的文章中的段落(例如[p id =“1”]),除了最后一段,[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;
它有效,但当我报告错误时,我收到以下错误未定义的偏移:2 。这并不重要,但在我测试我的页面时,这有点令人讨厌。知道如何杀死它吗?
答案 0 :(得分:1)
我通过以下方式改进了正则表达式:
/<p( [^>]+)?>/i
( [^>]+)?
更改为([^>]*)
。这样您就没有可选组,但此组中的字符是可选的。这意味着你将永远拥有这个群体。~<p([^>]*)>~i
现在让我们攻击php代码:
$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);
请注意,我使用了带有引用use (&$c)
的闭包&
。这样我们就可以更新$c
。