2012-01-23 80 views
1

我有preg_match_all和str_replace函数有点问题PHP 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>2, hello <b>okay</b>3 

正确的结果应该是这样的:

hello <b>okay</b>, hello <b>okay</b>, hello <b>okay</b> 

任何人都可以帮忙吗? 谢谢!

回答

1

这是因为第一场比赛@user_name也会匹配@user_name2@user_name3(至少@user_name部分)。你写它的方式,它是按照它应该的方式工作的。你可能想看看preg_replace()。为了测试正则表达式模式,我总是使用My Regex Tester(这实际上不是我的,这只是它的名字)。下面是该网站的输出,完整的代码生成:

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> 
+0

嗨Crontab,感谢您的建议..我尝试使用'$ source = preg_replace('/'.$ result。'/',''。$ result。' (',$ source);'但结果是一样的。:( –

+0

我的意思是让你自己使用'preg_replace()'而不是使用'preg_match_all()'和'str_replace()'串联。 – Crontab

+0

hmm,如果我不使用'preg_match_all',我不知道用什么字符串跟@ @必须替换为..?它怎么样? –

0

你的问题是不是与preg_match_all或的preg_replace。问题在于str_replace。 创建搜索阵列后,第一个标记包含的值为“user_name”,并且str_replace函数将字符串中的所有三次出现都替换掉。所以1和2的值仍然是字符串。

如果你改变你的源作为

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

它将很好地工作。否则你需要以相反的顺序迭代数组