开发者

String replace case insensitive exact matches from an array of words

开发者 https://www.devze.com 2023-03-29 16:04 出处:网络
In PHP, I have an array of words I would like to search and replace for case insensitive exact matches in a string.Example:

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 FOUND

I 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);
0

精彩评论

暂无评论...
验证码 换一张
取 消