开发者

How can I combine my two regular expressions and save the results as variable?

开发者 https://www.devze.com 2023-02-21 12:14 出处:网络
I get all the images with this preg_match_all(\'!http://.+\\.(?:jpe?g|png|gif)!Ui\' , $content , $matches);

I get all the images with this

preg_match_all('!http://.+\.(?:jpe?g|png|gif)!Ui' , $content , $matches);

and this is how i block all the image if it has a "bad word"

'/(list|of|bad|words)/i'

How can I combine them and save the result inst开发者_运维技巧ead in variable instead of print_r? My purpose is to delete from content all those images and produce the "clean" content.

Thank you!


Probably the fastest way is to run the first regex and then filter out the bad ones later. You could probably do this with a callback rather easily. I wouldn't try to combine the regex though.


Might require some tweaking depending on how $content is formatted:

<?php
    $content = 'http://www.example.com/images/image001.jpg 
                http://www.example.com/images/image002.jpeg 
                http://www.example.com/images/list001.jpg 
                http://www.example.com/images/image003.png 
                http://www.example.com/images/bad002.png 
                http://www.example.com/images/image004.gif 
                http://www.example.com/images/words003.jpg';

    preg_match_all('!http://.+\.(?:jpe?g|png|gif)!Ui', $content, $matches);

    preg_match_all('/\S+(list|of|bad|words)\S+/i', $content, $bads);

    $filtered = array_values(array_diff($matches[0], $bads[0]));

    print_r($filtered);
?>

Output:

Array
(
    [0] => http://www.example.com/images/image001.jpg
    [1] => http://www.example.com/images/image002.jpeg
    [2] => http://www.example.com/images/image003.png
    [3] => http://www.example.com/images/image004.gif
)
0

精彩评论

暂无评论...
验证码 换一张
取 消