关于php:用多维数组中的用户输入替换文本正文中的单词

Substituting Words in a Body of Text with User Input via Multidimensional Arrays

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
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
        )
)

另一个包含用什么替换这些匹配项:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
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>
        )
)

为了举例说明,我们假设正文是:

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

php函数preg_replace不处理多维数组,那么我该如何完成这个任务呢?


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

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

$reg_cats是带有regex的数组,$rep_cats是带有替换的数组。因为它们有相同的键和相同大小的子数组,所以可以这样做。

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

1
2
3
4
5
$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);


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

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

然后执行更换:

1
preg_replace($search, $replace, $string);


您需要将这些转换成它可以使用的数组。像这样。

1
2
3
4
5
6
7
8
9
$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);