php str_replace and \b word boundary

前端 未结 2 994
旧时难觅i
旧时难觅i 2021-01-22 05:14

I am trying to use str_replace, but can\'t figure out how to use \\b for word boundary:



        
2条回答
  •  不思量自难忘°
    2021-01-22 05:41

    You cannot use \b with str_replace(). The word boundary "\b" is only a valid anchor in regular expressions. So use preg_replace(), it's more appropriate should your search text contain natural language:

     $replace = array_combine($search, $replace);
     preg_replace('#\b('.implode('|',$search).')\b#e', '$replace["$1"]?:"$1"', $str)
    

    Otherwise any occourence of "E" in the text will get replaced with "East". As alternative you could at least add a space right hand to your $search and $replace strings.

提交回复
热议问题