Ivan RL
Ivan RL

Reputation: 81

REGEX for capturing these types of URLs

I'm trying to do a regex that will capture any url that begins with either http or https, and ends in jpg/png/gif. A SQL call is being made to the database which returns the uncooked text of a post.

The uncooked code:

$row['rawtopic'] = "XYZ TESTING PURPOSES + + http://i.imgur.com/filler_data.jpg + + We are currently...";

The regex:

$output_2 = preg_match_all( '/(https?://[^ ]+?(?:.jpg|.png|.gif)$)/i', $row['rawtopic'], $matches);

When I check for outputs in $matches[0], $matches[0][0] and $output_2, I don't get anything returned, i.e. nothing is being matched. I have tested to make sure that the regex works in https://regex101.com/#pcre, as well as by replacing $row['rawtopic'] with the actual URL itself.

Does anyone have any ideas as to why this could be?

Upvotes: 0

Views: 29

Answers (1)

RomanPerekhrest
RomanPerekhrest

Reputation: 92884

There were a few mistakes in your regexp. Change it as shown below:

// I've added one more url into the string (just for test)
$row['rawtopic'] = "XYZ TESTING PURPOSES + + http://i.imgur.com/filler_data.jpg + + We are currently... https://i.imgur.com/filler_data_test.jpg";

preg_match_all( '/\bhttps?:\/\/[^\s]+?\.(jpg|png|gif)\b/iu', $row['rawtopic'], $matches);

print_r($matches[0]);

The output:

Array
(
    [0] => http://i.imgur.com/filler_data.jpg
    [1] => https://i.imgur.com/filler_data_test.jpg
)

Upvotes: 1

Related Questions