1

我有两组数据存储在多维数组中。一个存储正则表达式,用于在较大的文本正文中查找整个单词:

Array
(
    [red] => Array
        (
            [0] => ~\b(a)\b~i
            [1] => ~\b(b)\b~i
            [2] => ~\b(c)\b~i
        )
    [orange] => Array
        (
            [0] => ~\b(d)\b~i
        )
    [green] => Array
        (
            [0] => ~\b(e)\b~i
        )
)

另一个包含替换这些匹配项的内容:

Array
  (
    [red] => Array
        (
            [0] => <span class="red">A</span>
            [1] => <span class="red">B</span>
            [2] => <span class="red">C</span>
        )
    [orange] => Array
        (
            [0] => <span class="orange">D</span>
        )
    [green] => Array
        (
            [0] => <span class="green">E</span>
        )
)

出于示例目的,假设正文是:

敏捷的棕色狐狸跳过了懒狗。a 敏捷的棕色狐狸跳过懒惰的狗。b 敏捷的棕色狐狸跳过懒惰的狗。c 敏捷的棕色狐狸跳过懒惰的狗。d 敏捷的棕色狐狸跳过懒惰的狗。e

PHP 函数preg_replace不处理多维数组,那么我将如何实现呢?

4

3 回答 3

1

要处理您的数组,只需使用 foreach 循环:

foreach($reg_cats as $key=>$reg_cat) {
    $yourstring = preg_replace($reg_cat, $rep_cats[$key], $yourstring);
}

$reg_cats是带有正则表达式的数组,$rep_cats是带有替换的数组。由于它们具有相同的键并且子数组具有相同的大小,因此您可以这样做。

如果您不需要转换匹配的内容(在这里您想将字母更改为大写),您可以使用单个关联数组:

$corr = array('<span class="red">$0</span>'    =>  '~\b(?:a|b|c)\b~i',
              '<span class="orange">$0</span>' =>  '~\bd\b~i',
              '<span class="green">$0</span>'  =>  '~\be\b~i');

$result = preg_replace($corr, array_keys($corr), $yourstring);
于 2013-06-16T01:16:10.873 回答
0

你需要把它们变成它可以使用的数组。像这样的东西。

$r=array();$s=$r;$n=0;
foreach($Second_array_you_didn_t_name as $kk => $vv)
    foreach($vv as $k => $v)
    {
      $r[++$n]=$v;
      $s[$n]=$First_array_you_didn_t_name[$kk][$k]
    }
$tqbf="The quick brown fox jumps over the lazy dog. a The quick brown fox jumps over the lazy dog. b The quick brown fox jumps over the lazy dog. c The quick brown fox jumps over the lazy dog. d The quick brown fox jumps over the lazy dog. e";
print preg_replace($r,$s,$tqbf);
于 2013-06-16T01:47:06.207 回答
0

假设两个阵列的形状相似,只需将两个阵列展平,如下所示:

$search = call_user_func_array('array_merge', $search);
$replace = call_user_func_array('array_merge', $replace);

然后执行替换:

preg_replace($search, $replace, $string);
于 2013-06-16T04:43:46.993 回答