PHP preg_match_all和str_replace

PHP preg_match_all和str_replace,php,str-replace,Php,Str Replace,我对preg_match_all和str_replace有点问题 <? $source = 'hello @user_name, hello @user_name2, hello @user_name3'; preg_match_all("/@[\w\d_]*/s", $source, $search); foreach($search[0] as $result) { $source = str_replace($result, "<b>

我对preg_match_all和str_replace有点问题

<?
    $source = 'hello @user_name, hello @user_name2, hello @user_name3';
    preg_match_all("/@[\w\d_]*/s", $source, $search);
    foreach($search[0] as $result) {
        $source = str_replace($result, "<b>okay</b>", $source);
    }

    echo $source;
?>

结果是(错误的):

你好,好的,好的,好的
正确的结果应该是这样的:

hello <b>okay</b>, hello <b>okay</b>, hello <b>okay</b>
你好好,你好好,你好好 有人能帮忙吗?
谢谢

这是因为第一个匹配项,
@user\u name
,也将匹配
@user\u name2
@user\u name3
(至少是
@user\u name
部分)。按照你写的方式,它按预期工作。你可能想看看。为了测试正则表达式模式,我总是使用(这实际上不是我的,这只是它的名字)。以下是该站点的输出,以及生成的代码:

Raw Match Pattern:
@[\w\d_]*

Raw Replace Pattern:
okay

PHP Code Example: 
<?php
$sourcestring="hello @user_name, hello @user_name2, hello @user_name3";
echo preg_replace('/@[\w\d_]*/s','<b>okay</b>',$sourcestring);
?>

$sourcestring after replacement:
hello <b>okay</b>, hello <b>okay</b>, hello <b>okay</b>
原始匹配模式:
@[\w\d\]*
原始替换模式:
可以
PHP代码示例:
替换后的$sourcestring:
你好好,你好好,你好好

之所以发生这种情况,是因为第一个匹配项,
@user\u name
,也将匹配
@user\u name2
@user\u name3
(至少是
@user\u name
部分)。按照你写的方式,它按预期工作。你可能想看看。为了测试正则表达式模式,我总是使用(这实际上不是我的,这只是它的名字)。以下是该站点的输出,以及生成的代码:

Raw Match Pattern:
@[\w\d_]*

Raw Replace Pattern:
okay

PHP Code Example: 
<?php
$sourcestring="hello @user_name, hello @user_name2, hello @user_name3";
echo preg_replace('/@[\w\d_]*/s','<b>okay</b>',$sourcestring);
?>

$sourcestring after replacement:
hello <b>okay</b>, hello <b>okay</b>, hello <b>okay</b>
原始匹配模式:
@[\w\d\]*
原始替换模式:
可以
PHP代码示例:
替换后的$sourcestring:
你好好,你好好,你好好

您的问题不在于preg\u match\u all或preg\u replace。问题在于str_替换。 创建搜索数组后,第一个标记包含值“user_name”,并且str_replace函数替换字符串中的所有三个匹配项。所以1和2的值保持在字符串中

如果您将源更改为

$source = 'hello @user_name1, hello @user_name2, hello @user_name3';

它会很好用的。否则您需要以相反的顺序迭代数组

您的问题不在于preg\u match\u all或preg\u replace。问题在于str_替换。 创建搜索数组后,第一个标记包含值“user_name”,并且str_replace函数替换字符串中的所有三个匹配项。所以1和2的值保持在字符串中

如果您将源更改为

$source = 'hello @user_name1, hello @user_name2, hello @user_name3';

它会很好用的。否则,您需要以相反的顺序迭代数组

hi Crontab,谢谢您的建议。。我尝试使用“$source=preg_replace”(“/”.$result.“/”、“.$result.”、$source);”但结果是一样的(我的意思是让你自己使用
preg\u replace()
,而不是使用
preg\u match\u all()
str\u replace())
in tandem.hmm,如果我不使用
preg_match_all
,我不知道后面跟
@
的字符串必须替换为什么?怎么样?嗨,Crontab,谢谢你的建议..我试着使用“$source=preg_replace”(“/”.$result.”,“.$result.”,$source);`但结果是一样的..:(我想让你使用
preg_replace()
本身,而不是使用
preg\u match\u all()
str\u replace()
串联。嗯,如果我没有使用
preg\u match\u all
,我不知道后面跟
@
的字符串必须替换为..?怎么回事?