Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Unexpected behavior of preg_replace_callback

I think the preg_replace_callback function of php has a runtime problem :

$a = [
        'test.db',
        'WhatsApp Image 2021-10-21 at 18.52.14.jpeg',
        'WhatsApp Image 2021-10-21 at 18.52.15.jpeg',
        'WhatsApp Image 2021-10-21 at 18.52.16.jpeg',
        'WhatsApp Image 2021-10-21 at 18.52.18 (1).jpeg',
        
       ];
    
     $callback = function ($matches) {
            return $matches[0];
        };
        
    $c = preg_replace_callback('/.*\.[jp][pn]e?g/i', $callback, $a );
        
    print_r($c);

return :

Array
(
    [0] => test.db
    [1] => WhatsApp Image 2021-10-21 at 18.52.14.jpeg
    [2] => WhatsApp Image 2021-10-21 at 18.52.15.jpeg
    [3] => WhatsApp Image 2021-10-21 at 18.52.16.jpeg
    [4] => WhatsApp Image 2021-10-21 at 18.52.18 (1).jpeg
)

Why is test.db still present when even when I parse the return $matches[0] it never fits inside ?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

preg_replace_callback runs a replacement on each item in the array, but if there’s nothing to replace, it still returns the element unchanged.

preg_filter is what you need.

preg_filter() is identical to preg_replace() except it only returns the (possibly transformed) subjects where there was a match.

Side note: /.*\.[jp][pn]e?g/i will match foo.jpg.exe. You probably want /.*\.[jp][pn]e?g$/i instead.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading