我如何获得preg_match_all();来自URL

时间:2016-02-17 09:09:43

标签: php

这是我的网址:

<a href="http://sbayjai.com/forum/index.php?topic=67433.0">test_curl</a>

我想使用preg_match_all();来获取

http://sbayjai.com/forum/index.php?topic=67433.0

感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

您可以使用以下正则表达式:

$text = '<a href="http://sbayjai.com/forum/index.php?topic=67433.0">test_curl</a>';
$regex = '<a\s[^>]*href=(\"??)([^\" >]*?)\\1[^>]*>(.*)<\/a>';

if(preg_match_all("/$regex/siU", $text, $matches)) {
  // urls
  var_dump($matches[2]);
  // link text
  var_dump($matches[3]);
}

输出:

array(1) {
  [0]=>
  string(48) "http://sbayjai.com/forum/index.php?topic=67433.0"
}
array(1) {
  [0]=>
  string(9) "test_curl"
}

正则表达式取自http://www.the-art-of-web.com/php/parse-links/,如果您有兴趣了解其工作原理,可以在这里找到所有细节的非常好的解释。