Thursday, 30 August 2018

preg_replace insensitive to cases using two tables to replace the first match

I need something like this:

$string = "That's a big apple, a red apple";
$arr = array(apple, lemon);
$arr2 = array(APPLE, LEMON);
preg_replace('/($arr)/i', $arr2, $string, 1);
//output = That's a big APPLE, a red apple

It means replace words for uppercase using arrays but only the first match, case-insensitive.

Your first variable is not correct, if its an array each value needs to be a regex
$arr = array('/\b(apple)\b/i', '/\b(lemon)\b/i');
$arr2 = array('APPLE', 'LEMON');

preg_replace($arr, $arr2, $string, 1);

Edit: I updated this to include word boundries which may help in some instances

0 comments:

Post a Comment