phpregexurl

Match question mark and everything after


I'm trying to use preg_replace to create image links from urls.

Example: https://www.google.com/image.png becomes <img src="https://www.google.com/image.png">

$patterns = array (
'~https?://\S+?(?:png|gif|webp|jpe?g)~'
);
$replace = array (
'<div><img src="$0" style="width:100%;object-fit:contain;"></div>'
);
$string = preg_replace($patterns, $replace, $string);

I stripped out the irrelevant parts for brevity, but that's an array for a reason.

This works great, unless the image has a question mark in it... ie,

https://www.google.com/image.png?123456

In this case, the question mark and everything after it will not match... so we wind up with:

<div><img src="https://www.google.com/image.png"></div>?123456

How can I get it to match the question mark as well?


Solution

  • You can add an optional capturing group that starts with the ? character:

    $patterns = array (
       '~https?://\S+?(?:png|gif|webp|jpe?g)(\?\S+)?~'
       # Here ------------------------------^
    );