如果我有这个字符串:
I am a @test and I am another@test
我想用另一个字符串替换所有带有SPACES的@words实例。
所以上面变成了
I am a @replace and I am another@test
最后一部分未被替换,因为@
前面没有空格我也试图通过循环数组来解决这个问题。我的代码如下,但正则表达式不正确:
$mentioned = [[0] => "@test", [1] => "@anotherword"];
$tweet = "This is a tweet with @test in it and also @anotherword";
foreach ($mentioned as &$mention) {
$mention = "@".$mention;
$mention_link = "<a href='#'>".$mention.'</a>';
preg_replace('/ (@) /', $mention_link, $tweet);
}
答案 0 :(得分:1)
您需要搜索此正则表达式:
(?<!\w)@test
并替换为:
@replace
<强>代码:强>
$result = preg_replace('/(?<!\w)@test/im', '@replace', $input);
答案 1 :(得分:0)
(?<=\s)@\S+
您可以使用这个简单的正则表达式来完成这项工作。参见演示。
http://regex101.com/r/tF5fT5/35
$re = "/(?<=\\s)@\\S+/im";
$str = "I am a @test and I am another@test";
$subst = "@replaced";
$result = preg_replace($re, $subst, $str);