KaLv1n K
KaLv1n K

Reputation: 131

PHP preg_match_all and str_replace

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!

Upvotes: 1

Views: 1518

Answers (2)

WWW
WWW

Reputation: 9860

It's happening because the first match, @user_name, will also match @user_name2 and @user_name3 (at least the @user_name part). 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:

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>

Upvotes: 1

Umesh Chavan
Umesh Chavan

Reputation: 614

You problem is not with preg_match_all or preg_replace. The Problem is with str_replace. After you created an search array, the first token contains value as "user_name", and str_replace function replace all three occurrences from the string. so 1 and 2 value remains as it is in string.

If you change your source as

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

it will work fine. otherwise you need to iterate array in reverse order

Upvotes: 0

Related Questions