获取字符串部分后面的整数


Get the integer following part of a string?

我有一堆字符串,可能有也可能没有类似于以下内容的子字符串:

<a class="tag" href="http://www.yahoo.com/5"> blah blah ...</a>

我试图检索链接末尾的"5"(不一定是一位数字,它可能很大)。但是,此字符串会有所不同。链接之前和之后的文本将始终不同。唯一相同的是<a class="tag" href="http://www.yahoo.com/和关闭</a>

您可以使用

preg_match_all<a class="tag" href="http:'/'/(.*)'/('d+)">正则表达式来完成。

试一试parse_url()。从那里应该很容易。

由于您只需要检索 5,因此非常简单:

$r = pret_match_all('~'/('d+)"~', $subject, $matches);

然后,它位于第一个匹配组中。

如果您需要更多信息,例如链接文本,我建议您为此使用HTML解析器:

require('Net/URL2.php');
$doc = new DOMDocument();
$doc->loadHTML('<a class="tag" href="http://www.yahoo.com/5"> blah blah ...</a>');
foreach ($doc->getElementsByTagName('a') as $link)
{
    $url = new Net_URL2($link->getAttribute('href'));
    if ($url->getHost() === 'www.yahoo.com') {
        $path = $url->getPath();
        printf("%s (from %s)'n", basename($path), $url);
    }
}

示例输出:

5 (from http://www.yahoo.com/5)

我会得到"basename":

// prints passwd
print basename("/etc/passwd")

要获取链接,您可以使用:

$xml  = simplexml_load_string( '<a class="tag" href="http://www.yahoo.com/5"> blah blah ...</a>' );
$attr = $xml->attributes();
print $attr['href'];

最后:如果你不知道字符串的整个结构,请使用这个:

$dom = new DOMDocument;
$dom->loadHTML( '<a class="tag" href="http://www.yahoo.com/5"> blah blah ...</a>asasasa<a class="tag" href="http://www.yahoo.com/6"> blah blah ...</a>' );
$nodes = $dom->getElementsByTagName('a');
foreach ($nodes as $node) {
    print $node->getAttribute('href');
    print basename( $node->getAttribute('href') );
}

因为这也将修复无效的 HTML 代码。