Had to deploy some PHP code onto a shared server with only PHP5.2.8. All code works EXCEPT for the preg_filter()
call which was added in 5.3+ (and against which the code was written).
Can anyone recommend an easy substitute开发者_StackOverflow for preg_filter()
in PHP5.2?
PHP manual says that preg_filter()
is identical to preg_replace()
except it only returns the matches.
So, you can use a combination of preg_replace
and array_diff
to get results like preg_filter in PHP 5.2.x. Do it like this:
<?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);
?>
This gives the output (with xDebug installed):
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)
Which is same as preg_filter()
output:
Array
(
[0] => A:C:1
[1] => B:C:a
[2] => A:2
[3] => B:b
[4] => A:3
[7] => A:4
)
精彩评论