Jump to content

Finding a url within a lot of text


franzy_pan

Recommended Posts

Hi all,

 

I'm just wondering if there is a way to locate a url written as HTML e.g. <a href="http://www.abcd.com/">Link</a> within a descriptive text description.  I only need the bit from the first " to the last " to allow me to change the url.

 

I can't figure out how to search for it whilst ensuring that I have the URL in its entirety.

 

Example text description:

 

<p>Win two smiley faces.</p><br />

Click here: <a href="http://www.abcd.com/">Link</a>

 

Any assistance or help would be greatfully recieved - thank you.

 

Franzy Pan ??? ???

Link to comment
https://forums.phpfreaks.com/topic/107766-finding-a-url-within-a-lot-of-text/
Share on other sites

You can use RegEx (preg_replace):

 

<?php
$str = 'bla bla <a href="http://oldurl.com/">link text</a> bla bla.';
$pattern = '|(?<=href=").*?(?=")|s';
$replacement = 'http://newurl.com/';
$str = preg_replace($pattern, $replacement, $str);
echo $str;
?>

 

For the search, I'm using a positive lookbehind (?<=string) which means the URL we're looking for (the following greedy .*? part) must be preceded by href=". Then I'm using a positive lookahead (?=string) which means the URL match will end at the first double quote encountered. The trick about lookbehinds and lookaheads is, that those parts aren't matched, which means that we can replace the match (= the whole URL only) with the new URL. Further reading: http://www.regular-expressions.info/lookaround.html

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.