Php 搜索并替换字符串中以@符号开头的每个唯一单词,即使它们是';相似的

Php 搜索并替换字符串中以@符号开头的每个唯一单词,即使它们是';相似的,php,regex,Php,Regex,我要替换以@开头的字符串中的所有匹配项。如果我使用str_replace,那么在用户名变得相似之前,一切都可以正常工作。我需要一些东西来完全替换这些独特的词,而不影响其他类似的词。例如@johnny和@johnny会有问题。也许regex能帮上忙 function myMentions($str){ $str = "Hello @johnny, how is @johnnys doing?"; //let's say this is our param $regex = "~

我要替换以@开头的字符串中的所有匹配项。如果我使用str_replace,那么在用户名变得相似之前,一切都可以正常工作。我需要一些东西来完全替换这些独特的词,而不影响其他类似的词。例如@johnny和@johnny会有问题。也许regex能帮上忙

function myMentions($str){
    $str = "Hello @johnny, how is @johnnys doing?"; //let's say this is our param

     $regex = "~(@\w+)~"; //my regex to extract all words beginning with @ 

            if(preg_match_all($regex, $str, $matches, PREG_PATTERN_ORDER)){ 

                foreach($matches[1] as $matches){ //iterate over match results

    $link = "<a href='www.google.com'>$matches</a>"; //wrap my matches in links

    $str = str_replace($matches,$link,$str); //replace matches with links

    }
    }
    return $str;
}
函数mynotices($str){
$str=“你好@johnny,@johnny怎么样?”;//假设这是我们的情人
$regex=“~(@\w+)”;//我的regex提取以@
如果(preg_match_all($regex,$str,$matches,preg_PATTERN_ORDER)){
foreach($matches[1]作为$matches){//迭代匹配结果
$link=”“;//将我的匹配项包装在链接中
$str=str_replace($matches,$link,$str);//用链接替换匹配项
}
}
返回$str;
}
输出应该是:
你好,最近怎么样?

相反,我得到的是:
你好,最近怎么样?
(注意:@johnny上的额外“s”不是换行符)


它没有意识到@johnny和@johnny是两个不同的词,所以str_一次就把这两个词替换为。基本上,函数是一次取一个单词并替换所有相似的单词。

您的代码不必要地复杂,您只需要一个
preg\u replace

function myMentions($str){
     return preg_replace("~@\w+~", "<a href='www.google.com'>\$0</a>", $str);
}

$str = "Hello @johnny, how is @johnnys doing?";
echo myMentions($str);
// => Hello <a href='www.google.com'>@johnny</a>, how is <a href='www.google.com'>@johnnys</a> doing?
函数mynotices($str){
返回preg\u replace(“~@\w+~”,“”,$str);
}
$str=“你好@johnny,@johnny怎么样?”;
回音我提到($str);
//=>你好,最近怎么样?


preg\u replace(“~@\w+~”,“,$str)
匹配所有非重叠出现的
@
+1个或多个单词字符,并用
文本包装它们。请注意,
$0
是对整个比赛的反向引用。

您尝试了哪些方法来解决此问题?这个替换背后的规则是什么?我必须在foreach中工作,因为我要把每个用户id都放在链接中。您的解决方案用于包装所有相似的单词,但是每个相似的单词在foreach中返回相同的id,所以现在我将致力于解决这个问题。非常感谢,伙计:)@XpressPHP您不需要任何foreach。如果通过将提及值作为键传递给某个字典(关联数组,例如
$dic=['johnny'=>'300923','johnny'=>'999923']
)来检索值,则需要
返回preg\u replace\u回调(~@(\w+),函数($m)use($dic){return”“;},$str)。看见