Forum Moderators: coopster

Message Too Old, No Replies

preg match all search for links

         

danbhala

11:20 am on Oct 5, 2007 (gmt 0)

10+ Year Member



Hi,

I'd like search a string for a link

for example

The following link is in the string

<a href=http://mysite.com/page.php><img src="http://mysite.com/img.gif" /></a>

i'd like to search the entire string for that specific url. then would like to get the location of the image that is inside the <a> tag

could anyone help?!

PHP_Chimp

1:50 pm on Oct 5, 2007 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



You could use preg_match [uk3.php.net] to find the matching parts. You just need to get the expression correct.
Give this a try -
<?php
$a = '<a href="http://example.com/page.php"><img src="http://example.com/img.gif" /></a>'; // your link with " " around the href attribute ;)
$p = '%^(?i)<a(?:.*)?href="(.*)"(?:.*)?>\s*<img(?:.*)?src="(.*)"(?:.*)?/?>\s*</a>$%';

preg_match($p, $a, $matches);

print_r($matches);
?>

Output =

Array ( [0] => *actual link in here* => http://example.com/page.php [2] => http://example.com/img.gif )

However there is a note in the manual -


Do not use preg_match() if you only want to check if one string is contained in another string. Use strpos() or strstr() instead as they will be faster.

So I guess it depends on what you are doing with the results of the match if you will go for preg_match¦strpos¦strstr

[1][edited by: coopster at 4:33 pm (utc) on Oct. 8, 2007]
[edit reason] examplified [/edit]