-1

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.

Eddie D.
  • 145
  • 3
  • 12

4 Answers4

3

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

Chris Morrissey
  • 489
  • 2
  • 4
0

I would use strtr() instead of a regex:

$string = "That's a big apple, a red apple";
$string = strtr( $string, array( 'apple' => 'APPLE', 'lemon' => 'LEMON'));
nickb
  • 59,313
  • 13
  • 108
  • 143
0

There are a couple of issues with your code.

  • you need to quote the strings inside your array; otherwise, PHP will try to interpret them as constants

  • you can't just put the $arr variable in the regex string, you would need to loop through the array and use the string value of the array item in the preg_replace

  • preg_replace will replace all occurrences of regex

If you only want to replace the first occurs of the string you could try a combination of strpos and substr_replace

Ry-
  • 218,210
  • 55
  • 464
  • 476
MajorCaiger
  • 1,893
  • 1
  • 12
  • 18
0
$string = "That's a big apple, a red apple.";
$words = array('APPLE', 'LEMON');
foreach ($words as $word){
    $ini = stristr($string, $word, TRUE);
    if ($ini){
        $string = $ini.$word.substr($string, strlen($ini.$word));
        break;
    }
}
echo $string;

Output:

That's a big APPLE, a red apple.

Expedito
  • 7,771
  • 5
  • 30
  • 43