0

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?

4
  • Do you only want canonical URLs? I.E you only want URLs that start with http or do you also want URLs like www.google.com Commented Sep 19, 2016 at 16:19
  • I need the whole after "[1]:", the http://...someurl until space since te pattern above will be inside a text. Commented Sep 19, 2016 at 16:26
  • Example: Hi boy, how are you? This is my cat ![enter image description here][1] [1]: somewebsite.com/images/mycat.jpg I hope you love it. Commented Sep 19, 2016 at 16:28
  • @jose -- I added an answer that should get what you need, assuming the format is always the same Commented Sep 19, 2016 at 16:30

1 Answer 1

1

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. :(";
}

?>
Sign up to request clarification or add additional context in comments.

12 Comments

How about turning ![enter image description here][1] [1]: somewebsite.com/images/mycat.jpg into <img src="somewebsite.com/images/mycat.jpg ">
You want to extract the part after src?
Added to pull from src
No actually your answer is what I needed, to extract the url part, what happens is that I have a dynamic text, example "This is text that is going to be changin and it could have a reference to an image like this ![enter image description here][1] [1]: somewebsite.com/images/mycat.jpg so i need to turn that reference into an actual image"
Note that h-ttp:// part is erased by stackoverflow after the last [1]:
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.