Forum Moderators: coopster

Message Too Old, No Replies

retrieve URL array from $string

         

sssweb

5:09 pm on Sep 23, 2006 (gmt 0)

10+ Year Member



Is there a way to retrieve an array of URL's from a text string? For example:

$string = 'This is a <a href="www.site.com">string</a> of text with 2 URL's, one of which is [site2.com';...]

I want code that gives this array:

$url_array = array('www.site.com' , 'http://site2.com')

eelixduppy

3:11 pm on Sep 24, 2006 (gmt 0)



Something like this should so the trick. You may have to tweak the regex to fit your needs. This is just an example:

$string = 'This is a <a href="www.site.com">string</a><br />';
$string .= '<a href="monkey.html">monkey</a> fishsticks';
$found = array();
$pattern = '/<a href="(.*)">.*<\/a>/iU';
[url=http://us3.php.net/manual/en/function.preg-match-all.php]preg_match_all[/url]($pattern,$string,$found);
$urls = $found[1];
echo '<pre>';
print_r($urls);
echo '</pre>';

Good luck!

orion_rus

3:17 pm on Sep 24, 2006 (gmt 0)

10+ Year Member



preg_match("#href='?\"?([^ \"'><#]*)'?\"#i",$string,$matches);
print_r($matches);

u have www.site.com in $matches[1];

then just make
$matches[1]="http://".str_replace("http://","",$matches[1]);

and u get align address
good luch to you

eelixduppy

3:35 pm on Sep 24, 2006 (gmt 0)



orion_rus,

preg_match() will stop searching after the first match. preg_match_all() on the contrary will continue until it reaches the end of subject.

sssweb

6:10 pm on Sep 24, 2006 (gmt 0)

10+ Year Member



Thank you guys; I can work it out from here.

orion_rus

7:36 pm on Sep 24, 2006 (gmt 0)

10+ Year Member



eelixduppy

of cause it makes so, but he needs only first www, and u have some leaking in your syntaxis of pattern