【发布时间】:2011-12-03 03:28:11
【问题描述】:
我对正则表达式还是比较陌生,感觉我的代码太贪心了。我正在尝试将 id 属性添加到一段代码中的现有链接。我的功能是这样的:
function addClassHref($str) {
//$str = stripslashes($str);
$preg = "/<[\s]*a[\s]*href=[\s]*[\"\']?([\w.-]*)[\"\']?[^>]*>(.*?)<\/a>/i";
preg_match_all($preg, $str, $match);
foreach ($match[1] as $key => $val) {
$pattern[] = '/' . preg_quote($match[0][$key], '/') . '/';
$replace[] = "<a id='buttonRed' href='$val'>{$match[2][$key]}</a>";
}
return preg_replace($pattern, $replace, $str);
}
这会像我想要的那样添加 id 标签,但它会破坏超链接。例如:
如果原码是:<a href="http://www.google.com">Link</a>
而不是<a id="class" href="http://www.google.com">Link</a>
这是给予
<a id="class" href="http">Link</a>
有什么建议或想法吗?
【问题讨论】:
-
id属性必须是唯一的。你应该使用preg_replace_callback而不是先匹配然后使用preg_replace。 -
你没有要求它,并且对于输出修改它通常是愚蠢的,所以评论:如果没有正则表达式,这会更简单,例如查询路径
htmlqp($html)->find("a") FOREACH attr("id", "buttonRed".($i++));
标签: php class href preg-match-all