我在我的数据中找到某些词,并用锚标记替换这些关键字。
。关键字:迪斯尼
数据:
This is temp data -disney-movie-deaths.html nightmare some more text disney This is some more data.
我想把它转换成:
This is temp data -disney-movie-deaths.html nightmare some more text <a href="/test.php">disney</a> This is some more
我使用regx作为:/bdisneyb/i
但问题是它将其转换为:
This is temp data -<a href="/test.php">disney</a>-movie-deaths.html nightmare some more text disney This is some more
有人能面对这类问题吗?
你的逻辑是合理的,但在你的情况下,单词边界是不够的。您看到bdisneyb
匹配-disney- (为什么不呢?)对于您的示例,我在您要匹配的单词后面和之后添加了一些空格:
$result = preg_replace('/s+(disney)s+/', '<a href="/test.php">$1</a>', $subject);
虽然这将在本例中工作,但它可能还不够。例如,它将不能与disney.
工作,您可以根据您的需要修改它。
用s代替b
/sdisneys/i
b表示字边界,并包含"-"作为匹配字符
http://www.regular-expressions.info/wordboundaries.html您要确保disney
本身是一个单词。下面是我使用的正则表达式:
[s.]disney[s.$]
我是这样测试的:
http://rubular.com/r/YyZMeGITJY我想这可能行得通:
preg_replace("#(?:s|A)(disney)(?:s|z)#m", "<a>1</a>", $text);