必须使用PHP5.2.8将一些PHP代码部署到共享服务器上。对于preg_filter()
调用,所有代码的工作都是例外,该调用是在5.3+中添加的(编写代码时也是如此)。
有人建议在PHP5.2中轻松替换preg_filter()
吗?
答案 0 :(得分:6)
PHP手册说preg_filter()
与preg_replace()
相同,只是它只返回匹配。
因此,您可以使用preg_replace
和array_diff
的组合来获取PHP 5.2.x中的preg_filter等结果。这样做:
<?php
$subject = array('1', 'a', '2', 'b', '3', 'A', 'B', '4');
$pattern = array('/\d/', '/[a-z]/', '/[1a]/');
$replace = array('A:$0', 'B:$0', 'C:$0');
$result = preg_replace($pattern, $replace, $subject);
var_dump($result);
//take difference of preg_replace result and subject
$preg_filter_similar = array_diff($result, $subject);
var_dump($preg_filter_similar);
?>
这给出了输出(安装了xDebug):
array
0 => string 'A:C:1' (length=5)
1 => string 'B:C:a' (length=5)
2 => string 'A:2' (length=3)
3 => string 'B:b' (length=3)
4 => string 'A:3' (length=3)
5 => string 'A' (length=1)
6 => string 'B' (length=1)
7 => string 'A:4' (length=3)
array
0 => string 'A:C:1' (length=5)
1 => string 'B:C:a' (length=5)
2 => string 'A:2' (length=3)
3 => string 'B:b' (length=3)
4 => string 'A:3' (length=3)
7 => string 'A:4' (length=3)
Array
(
[0] => A:C:1
[1] => B:C:a
[2] => A:2
[3] => B:b
[4] => A:3
[7] => A:4
)