如何在PHP中的字符串“ tag =”后获取数字

时间:2019-06-27 18:50:00

标签: php

我想获取“ tag =“之后的数字。

例如,在以下情况下,我想获取数字“ 123”

<li><a href='http://example.com/2019/?tag=123'>2019 &nbsp;(3)</a></li>
<li><a href='http://example.com/2018/?tag=123'>2018 &nbsp;(1)</a></li>
<li><a href='http://example.com/2017/?tag=123'>2018 &nbsp;(1)</a></li>
<li><a href='http://example.com/2016/?tag=123'>2018 &nbsp;(1)</a></li>

数字可以更改,但所有列出的数字都相同。
域和域可能会更改。

我尝试了类似下面的操作,但是被卡住了。

$get_number = explode("<li><a href='http://example.com/", $get_number);
$get_number = substr($get_number, ...);

感谢您的关注。

4 个答案:

答案 0 :(得分:1)

好的,您可以通过以下方式做到这一点:

  • 获取所有按年份分组的标签
$str = '<li><a href=\'http://example.com/2019/?tag=123\'>2019 &nbsp;(3)</a></li>
<li><a href=\'http://example.com/2018/?tag=123\'>2018 &nbsp;(1)</a></li>
<li><a href=\'http://example.com/2017/?tag=123\'>2018 &nbsp;(1)</a></li>
<li><a href=\'http://example.com/2016/?tag=123\'>2018 &nbsp;(1)</a></li>';
$matches = [];
preg_match_all('/\/(?<years>[0-9]+)\/\?tag=(?<tags>[0-9]+)/', $str, $matches);
var_dump($matches['years'], $matches['tags']);

演示:https://3v4l.org/bLob7

  • 只需通过此模式获取所有标签
$str = '<li><a href=\'http://example.com/2019/?tag=123\'>2019 &nbsp;(3)</a></li>
<li><a href=\'http://example.com/2018/?tag=123\'>2018 &nbsp;(1)</a></li>
<li><a href=\'http://example.com/2017/?tag=123\'>2018 &nbsp;(1)</a></li>
<li><a href=\'http://example.com/2016/?tag=123\'>2018 &nbsp;(1)</a></li>';
$matches = [];
preg_match_all('/tag=(?<tags>[0-9]+)/', $str, $matches);
var_dump($matches['tags']);

演示:https://3v4l.org/NT4Lo

答案 1 :(得分:1)

不能完全确定您的整个文档结构,但是可以使用DOMDocument来完成大部分工作。在此示例中,它使用getElementsByTagName()获取所有<a>标签,但是如果您需要更复杂的内容,则可以使用XPath查找相关项目。

然后提取href属性并将查询部分拆分出来(使用parse_url()PHP_URL_QUERY获得tag=123),然后使用parse_str()提取值的关联数组...

$doc = new DOMDocument();
$doc->loadHTML($html);

$aTags = $doc->getElementsByTagName("a");
foreach ( $aTags as $tag )  {
    parse_str(parse_url($tag->getAttribute("href"), PHP_URL_QUERY), $parts);
    echo $parts['tag'].PHP_EOL;
}

答案 2 :(得分:0)

又脏又短:

$result = array_filter(array_map('intval', explode('tag=', $string)));

RegExp(数字在$result[1]内部):

preg_match_all("#tag=(\d+)#", $string, $result);

答案 3 :(得分:0)

尝试这个。它可能满足您的要求

<?php


$a = new SimpleXMLElement('<a href="http://example.com/2019/?tag=123">Click here</a>');
$href= $a['href'];

$whatIWant = substr($href, strpos($href, "=") + 1);    
echo $whatIWant;
?>