Search code examples
phppreg-match-allsubstr

Find two different substr in PHP


From:

$str = "This is one string with this picture pic1.jpg and here there's another one pic2.png for example"

I want to use something similar to preg_match_all() but I would like to do it just in one line. I want to have in just one array both: [pic1.jpg] and [pic2.png].

Something like this:

preg_match_all(
'/picture (.*) and|one (.*) for/',
$pat,
$matches,
PREG_PATTERN_ORDER));

I know this code is really bad, but I think you have the idea.


Solution

  • This will match your intended image files with less flexibility (improved accuracy) in the file suffix and more flexibility in the filename.

    Pattern: (Demo) /\w+\.(?:gif|png|jpe?g)/i

    This will match one or more letters/numbers/underscores, followed by a dot, followed by gif, png, jpg, or jpeg (case-insensitively).

    If you require more file suffixes, you can extend the expression with another alternative by adding a pipe (|) then your suffix.

    If you need to include more possible characters to the front of the filename, you can create a character class like this [\w@!] which will also allow @ and !. Or you could change \w with \S to match all non-white-characters, but this will slow down your pattern a little.

    PHP Code: (Demo)

    $str="Match four pictures like this: pic1.jpg, pic2.png, pic3.gif, and pic4.jpeg for example, but not these: document5.pdf and excel7.xls.";
    var_export(preg_match_all('/\w+\.(?:gif|png|jpe?g)/i',$str,$out)?$out[0]:'failed');
    

    Output:

    array (
      0 => 'pic1.jpg',
      1 => 'pic2.png',
      2 => 'pic3.gif',
      3 => 'pic4.jpeg',
    )
    

    You will see that by tightening up the file suffix requirements, you can avoid unintentional matches which are not image files.