在 PHP 中的 span 标签内添加指向特定单词的链接
我有一个要添加链接的单词列表,我可以使用 preg_match_all 和 preg_replace 相当轻松地完成此操作:
$str = "<span class=\"cz\">Dám si jedno pivo prosím.</span> = I'll have a beer please.";
preg_match_all('/[a-zťúůýžáčďéěíňóřš]+/i',$str,$matches);
$matches = array_unique($matches[0]);
foreach ($matches as $match) {
if(!empty($words[$match])) {
$str = preg_replace("/(^|[^\w]){1}(".preg_quote($match,"/").")($|[^\w]){1}/i", '\\1<a href="#">\\2</a>\\3', $str);
}
}
echo $str;
我想做的是将链接限制为仅在 span 标记内。
我的大脑已经被正则表达式淘汰了,所以任何帮助将不胜感激!谢谢!
达伦.
I have a list of words that I'd like to add a link to, I can do this fairly easily using preg_match_all and preg_replace:
$str = "<span class=\"cz\">Dám si jedno pivo prosím.</span> = I'll have a beer please.";
preg_match_all('/[a-zťúůýžáčďéěíňóřš]+/i',$str,$matches);
$matches = array_unique($matches[0]);
foreach ($matches as $match) {
if(!empty($words[$match])) {
$str = preg_replace("/(^|[^\w]){1}(".preg_quote($match,"/").")($|[^\w]){1}/i", '\\1<a href="#">\\2</a>\\3', $str);
}
}
echo $str;
What I'd like to do is restrict the linking to only within the span tag.
My brain is all regex-ed out, so any help would be appreciated! Thanks!
Darren.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我认为这样的东西应该可以工作,但如果你的 SPAN 中有其他标签,就会破坏。我建议您改用 DOM 函数。
I think something like this should work, but will break if you have other tags inside your SPAN. I'd advise you to use the DOM functions instead.