给定部分链接值时如何提取链接

时间:2010-05-07 21:43:26

标签: php

我正在使用PHP 4,这是主机目前所拥有的。当给定部分链接进行查找时,如何从字符串中提取链接。

示例

$find_string = 'http://www.mysite.com/apple';  
$string = 'Something and something else 
          <a href="http://www.mysite.com/apple_banana">testlink</a> 
          something else and so forth 
          <a href="http://www.mysite.com/orange">orange</a>

在这种情况下,我想只提取其中包含http://www.mysite.com/apple的链接,以便检索http://www.mysite.com/apple_bananan

非常感谢任何帮助。

1 个答案:

答案 0 :(得分:0)

$matches = array();
$find_string = 'http://www.mysite.com/apple';
preg_match_all('!<\s*a\s*href="('.$find_string.'[^"]+)">!', 'Something and something else < a href="http://www.mysite.com/apple_banana">testlink< /a> something else and so forth < a href="http://www.mysite.com/orange">orange< /a> ', $matches);

print_r($matches);

/* output:

Array
(
    [0] => Array
        (
            [0] => < a href="http://www.mysite.com/apple_banana">
        )

    [1] => Array
        (
            [0] => http://www.mysite.com/apple_banana
        )

)

*/