preg_replace of "Word" in a sentence and "Word." on the end of a sentence

12,649

Not sure what the problem is. works for me.

<?
    $ret = 'I gave my Word to you Word.';
    $pattern = '/\bWord\b/i';
    $ret = preg_replace($pattern,"Heart",$ret);
    var_dump($ret);
?>

string(29) "I gave my Heart to you Heart."

Share:
12,649
kalimero
Author by

kalimero

Updated on November 20, 2022

Comments

  • kalimero
    kalimero over 1 year

    i want to preg_replace "Word" in PHP.

        $ret = 'I gave my Word to you.';    
        $pattern = '/\bWord\b/i';
        $ret = preg_replace($pattern,"Heart",$ret);
    // echo $ret; = "I gave my Heart to you";
    

    This works so far. But if the sentence is "I gave you my Word." or "I gave you my Word!" it doesn't change the "Word." into "Heart."

    • kennytm
      kennytm over 13 years
    • Fanis Hatzidakis
      Fanis Hatzidakis over 13 years
      If it's such a simple replacement perhaps str_replace is faster than the regular expression.
    • kennytm
      kennytm over 13 years
      @Fanis: str_replace won't detect word boundaries.
    • Fanis Hatzidakis
      Fanis Hatzidakis over 13 years
      @KennyTM you're absolutely right, I stand corrected.
  • Oliver O'Neill
    Oliver O'Neill over 13 years
    To add to this, \b word boundaries matches words with [a-zA-Z0-9_] characters.
  • kalimero
    kalimero over 13 years
    Hmm, when i put this in a single php file it works, in my other code not. maybe the problem is in some other code. thanks so far for open my eyes