2017-10-08 72 views
2

在我的網站上有一些看起來像這樣的網址。每次爆炸url的最後部分

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 

而且我需要得到befor其中包含一個隨機數.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 

當我只希望它返回此813478134881349

回答

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>'; 
} 
0

如果相同的格式有保證,可以通過-分裂一次,並與array_pop()獲得的最後一個元素:

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

Demo

1

它傳遞給這個函數:

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