i have a little problem about preg_match_all and 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;
?>
the result is (wrong):
hello <b>okay</b>, hello <b>okay</b>2, hello <b>okay</b>3
the right result should be like this:
hello <b>okay</b>, hello <b>okay</b>, hello <b>okay</b>
anyone can help?
Thanks!
It’s happening because the first match,
@user_name, will also match@user_name2and@user_name3(at least the@user_namepart). The way you’ve written it, it’s working as it’s supposed to. You might want to look at preg_replace(). To test regex patterns, I always use My Regex Tester (which isn’t actually mine, that’s just the name of it). Here’s output from that site, complete with code generated: