每次

时间:2017-10-08 23:44:40

标签: php

在我的网站上,我有一些看起来像这样的网址。

http://example.com/our-post-name-here-number-one-81347.html our post name number one 
http://example.com/our-post-name-here-number-two-81348.html our post name number two
http://example.com/our-post-name-here-number-three-81349.html our post name number three

我需要让.html包含一个随机数的部分正确,在任何情况下这个数字都不会相同。

目前,我将这些网址存储在.txt文件中,该文件也包含帖子的标题,并通过以下方法进行爆炸。

$array = explode("\n", file_get_contents('http://example.com/urls/delete.txt'));
foreach ($array  as $item) {
    $removed = "copyright";
    $nothing = "";
    $url = explode(" ", $item);
    $data = $url[0];
    $explode = explode(".html", $data);
    // other functions
    $primary =  $explode[0];
    print $primary; 
    print '<br>';
}

上面的代码目前正在返回此内容。

http://example.com/our-post-name-here-number-one-81347
http://example.com/our-post-name-here-number-two-81348
http://example.com/our-post-name-here-number-three-81349

当我只希望它返回此81347 81348 81349时。

3 个答案:

答案 0 :(得分:3)

我会使用正则表达式。

$array = explode("\n", file_get_contents('http://example.com/urls/delete.txt'));
foreach ($array  as $item)
{
    $regex = "/.*-([\d]+)\.html.*$/";
    preg_match ( $regex , $item , $matches );
    $primary =  $matches[1];

    print $primary; 
    print '<br>';
}  

答案 1 :(得分:1)

将其传递给此功能:

function url_post_id($url) {
    $i = strripos($url, "-");
    $j = stripos($url, ".", $i);
    return substr($url, $i+1, $j-$i-1);
}

答案 2 :(得分:0)

如果保证相同的格式,您可以再按-拆分一次,并使用array_pop()获取最后一个元素:

$pieces = explode("-", $primary);
$number = array_pop($pieces); 
print $number;

Demo

相关问题