views:

73

answers:

2

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 for preg_filter() in PHP5.2?

+2  A: 

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
)
shamittomar
Took a bit, but the concept here works.
Xepoch
+1  A: 

This works on the examples I can find, the compression of the pattern into a string might be a bit iffy - depending on the complexities of your patterns :)

function preg_filter($pattern,$replace,$subject,$limit=-1) {
    $step1=preg_replace($pattern,$replace,$subject,$limit);
    if (is_array($pattern)) {
        $pa=$pattern;
        $pattern="/";
        foreach ($pa as $p) {
            $pattern.=str_replace("/","",$p)."|";
        }
        $pattern=substr($pattern,0,-1)."/";
    }
    return preg_grep($pattern,$step1);
}

Or using array_diff:

function preg_filter($pattern,$replace,$subject,$limit=-1) {
    $step1=preg_replace($pattern,$replace,$subject,$limit);
    return array_diff($step1, $subject);
}
Rudu
Shamittomar's array_diff choice is more succinct - no need to compress pattern into a string. Depending on the scale of use, I wonder if there's a performance hit though.
Rudu