preg_replace不区分大小写,使用两个数组替换第一个匹配


preg_replace case insensitive using two arrays to replace the first match

我需要这样的东西:

$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

这意味着使用数组替换大写单词,但只替换第一个匹配的单词,不区分大小写。

如果第一个变量是数组,则每个值都需要是regex

$arr = array('/'b(apple)'b/i', '/'b(lemon)'b/i');
$arr2 = array('APPLE', 'LEMON');
preg_replace($arr, $arr2, $string, 1);

编辑:我更新了它,将单词bounddries包括在内,这在某些情况下可能会有所帮助

我会使用strtr()而不是正则表达式:

$string = "That's a big apple, a red apple";
$string = strtr( $string, array( 'apple' => 'APPLE', 'lemon' => 'LEMON'));

您的代码有几个问题。

  • 您需要引用数组中的字符串;否则,PHP将尝试将它们解释为常量

  • 不能只将$arr变量放在正则表达式字符串中,您需要循环遍历数组,并在preg_replace 中使用数组项的字符串值

  • preg_replace将替换所有出现的正则表达式

如果您只想替换字符串的第一个出现,您可以尝试strpossubstr_replace 的组合

$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;

输出:

那是一个大苹果,一个红苹果