jose
jose

Reputation: 39

replace a pattern to extract an image url from data php

I am trying to figure it out how to extract the url from this pattern

![enter image description here][1] [1]: http://www.codefixup.com/wp-content/uploads/2016/09/pattern-matching-in-php.png 

I just need the http part so I can place it inside an image tag. The image description could change, how can I do it with regex or preg_replace?

Upvotes: 0

Views: 224

Answers (1)

A_Elric
A_Elric

Reputation: 3568

Assuming that you wanted to capture the entire url the following should work

(?:\: )(?P<URL>.*)

Example: https://regex101.com/r/aV1fJ7/1

Note this would NOT work if you had a description that was like "Check out this cool dog: "

Or something along those lines.

I can make this more specific by doing...

(?:\[\d+]\: )(?P<URL>.*)

Live example of this working with more specific one: https://regex101.com/r/aV1fJ7/2

Example 3 to pull from an img src="" tag

(?:src=\")(?P<URL>.*)\"

https://regex101.com/r/aV1fJ7/3

And some example code showing how to capture, transform and output an image tag:

<?php

$urlstring ='![enter image description here][1] [1]: http://www.codefixup.com/wp-content/uploads/2016/09/pattern-matching-in-php.png';
$regex = '/ (?:\[\d+\]\: )(?P<URL>.*)/';
//echo $regex.'--'.$urlstring;
if (preg_match($regex, $urlstring, $matches)) {
    echo "img src=\"".$matches[1]."\"";
} else {
   echo "The regex pattern does not match. :(";
}

?>

Upvotes: 1

Related Questions