【问题标题】:How to find this url in the html with php?如何使用 php 在 html 中找到这个 url?
【发布时间】:2015-02-23 16:27:29
【问题描述】:

我想在一个 html 页面中找到一个特定的 url 并获得它的一部分。 网址在此页面中:

http://site1.com/games/arcade/139173-angry-birds-friends-1-7-0.html`

就像

http://download.site2.org/?server=2&apkid=com.rovio.angrybirdsfriends&ver=1.7.0

我想要它的 3 个部分:

  1. 2
  2. com.rovio.angrybirdsfriends
  3. 1.7.0

我的代码:

$html = file_get_contents("http://site1.com/games/name/139173-angry-birds-friends-1-7-0.html");
preg_match("/download(.*)/", $html, $results)
echo = $results[0];

【问题讨论】:

  • 错误 #1:使用正则表达式解析 html。使用 dom 解析器。
  • 第一个例子中的2应该从什么开始解析?
  • 网址在 $html = file_get_contents("site1.com/games/name/…);

标签: php regex preg-match file-get-contents


【解决方案1】:

这是你要找的吗?

$url = 'http://download.site2.org/?server=2&apkid=com.rovio.angrybirdsfriends&ver=1.7.0';

$query = parse_url($url, PHP_URL_QUERY);
parse_str($query, $params);

echo $params['server'], PHP_EOL;
echo $params['apkid'], PHP_EOL;
echo $params['ver'], PHP_EOL;

输出:

2
com.rovio.angrybirdsfriends
1.7.0

更新

// Read HTML
$html = file_get_contents(
    'http://getandroidapp.org/games/arcade/'
    . '139173-angry-birds-friends-1-7-0.html'
);

// Turn HTML into a DOM document
$dom = new DOMDocument();
@$dom->loadHTML($html); // Mute warnings

// Find anchor ...
foreach ($dom->getElementsByTagName('a') as $link) {
    $href = $link->getAttribute('href');

    // ... having a query part that starts with 'server='
    if (preg_match('#\?server=#', $href)) {
        $url = $href;

        // Parse query string from href
        $query = parse_url($url, PHP_URL_QUERY);
        parse_str($query, $params);

        // Display values
        echo $params['server'], PHP_EOL;
        echo $params['apkid'], PHP_EOL;
        echo $params['ver'], PHP_EOL;

        // One is enough
        break;
    }
}

输出:

2
com.rovio.angrybirdsfriends
1.7.0

这并不完全是万无一失的,但在你的情况下可能已经足够了。

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-06-15
  • 1970-01-01
  • 1970-01-01
  • 2017-08-13
  • 1970-01-01
  • 2021-11-07
相关资源
最近更新 更多