繁体   English   中英

PHP中的正则表达式问题

[英]Problems with Regular expressions in PHP

(我想让我的用户用他们的名字标记其他用户,这是问题:当某人再次编辑他的帖子时,他会在他的tinymce编辑器中获得链接。当他保存所做的编辑时,脚本将销毁旧链接...)

我将大字符串中的所有单词替换为数组中包含的单词。

$users = {'this', 'car'}
$text = hello, this is <a title="this" href="">a test this</a>
$search = '!\b('.implode('|', $users).')\b!i';
$replace =  '<a target="_blank" alt="$1" href="/user/$1">$1</a>';
$text = preg_replace($search, $replace, $text);

如您在上面看到的,我尝试将$ text中的“ this”和“ car”替换为

<a target="_blank" alt="$1" href="/user/$1">$1</a>

问题是,我的脚本在链接中时也替换了“ this”:

<a title="this" href="">this</a>

我不确定,但我想,您知道我的意思。 所以我的脚本破坏了我的链接...

我不需要检测该单词是否在html元素中,因为它应该能够替换h1或p等其他标签中的单词。

我需要类似模式的东西 ,只有当单词看起来像这样时才匹配:“ this”“ this,”“,this”“ this:” ...(没问题,如果我必须手动设置这些……)

另一个很棒的解决方案:一个字符串,我可以在其中设置不允许的html标签。

$ tags ='a,e,article';

招呼

这应该做

<.*?this.*?>(*SKIP)(*FAIL)|\b(this)\b

演示: https : //regex101.com/r/fX0pT1/1

有关此正则表达式方法的更多信息, 请访问http://www.rexegg.com/regex-best-trick.html

PHP用法:

$users = array('this', 'car');
$text = 'hello, this is <a title="this" href="">a test this</a>';
$terms = '(' . implode('|', $users) . ')';
$search = '!<.*?'.$terms.'.*?>(*SKIP)(*FAIL)|\b(' . $terms . ')\b!i';
echo $search;
$replace =  '<a target="_blank" alt="$2" href="/user/$2">$2</a>';
echo preg_replace($search, $replace, $text);

输出:

hello, <a target="_blank" alt="" href="/user/this">this</a> is <a title="this" href="">a test <a target="_blank" alt="" href="/user/this">this</a></a>

PHP演示: https : //eval.in/415964

...或者如果您只希望它用于链接, 请https://regex101.com/r/fX0pT1/2,<a。*?this。*?>(* <a.*?this.*?>(*SKIP)(*FAIL)|\\b(this)\\b

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM