String replace case insensitive exact matches from an array of words
In PHP, I have an array of words I would like to search and replace for case insensitive exact matches in a string. Example:
$pattern = array("base", "all");
$str = "first base baseball for all";
$str开发者_StackOverflow = str_ireplace($pattern, "FOUND", $str);
echo $str;
Outputs: first FOUND FOUNDbFOUND for FOUND
Expected: first FOUND baseball for FOUNDI don't want 'baseball' to be replaced because I'd only like whole words to be replaced. Is there a way to accomplish this?
Use preg_replace()
instead of str_ireplace()
for this, since you can define word boundaries in your regular expression.
$str = "first base baseball for all";
$pattern = '/\b(base|all)\b/i';
$str = preg_replace($pattern, "FOUND", $str);
echo $str;
// first FOUND baseball for FOUND
If you begin with an array, you can do this to build up the regex from the array:
$words = array('base','all');
// implode() words into a pipe-delimited string
$pattern = '/\b(' . implode("|", $words) . ')\b/i';
$str = preg_replace($pattern, "FOUND", $str);
精彩评论