2012-08-07 29 views
0

我有一大堆的字符串,可能会或可能不会有类似的子以下几点:获取字符串部分后的整数?

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

我试着检索“5”在链路的末端(即必要不是一位数号码,它可以是巨大的)。但是,这个字符串会有所不同。链接之前和之后的文本将始终不同。唯一相同的是<a class="tag" href="http://www.yahoo.com/和关闭</a>

回答

1

您可以使用preg_match_all<a class="tag" href="http:\/\/(.*)\/(\d+)">正则表达式。

0

我就得到了与“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代码。

+0

但我需要获得链接了字符串 – 2012-08-07 22:27:10

+0

嘿,我在评论时编辑了帖子。 :)我已经添加了两种不同的方法。最后一个应该适合你的问题。 – insertusernamehere 2012-08-07 22:37:53

0

因为你只需要检索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) 
+0

但我需要链接的字符串 – 2012-08-07 22:27:25

+0

在你写的问题你需要得到5,所以我带你的单词。对于链接,我建议一个HTML解析器:[稳健,成熟的HTML解析器的PHP](http://stackoverflow.com/questions/292926/robust-mature-html-parser-for-php) – hakre 2012-08-07 22:28:10

+0

“但是,这个字符串将链接之前和之后的文本将永远是不同的“ – 2012-08-07 22:29:18