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 |
另一个包含用什么替换这些匹配项:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
号
为了举例说明,我们假设正文是:
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函数
要处理数组,只需使用foreach循环:
1 2 3 | foreach($reg_cats as $key=>$reg_cat) { $yourstring = preg_replace($reg_cat, $rep_cats[$key], $yourstring); } |
如果不需要转换匹配的内容(此处您要将字母改为大写),则可以使用单个关联数组:
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 |
您需要将这些转换成它可以使用的数组。像这样。
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); |