2017-03-02 81 views
1

我有一個漂亮的url鏈接: www.abcd.com/Topic-V-CNHVNTNCHUUINP-Gangulys-waving-jersey-at-Lords-or-Dhonis-six-to-win-the-world-cup-- - 這是印度板球歷史上最大的贏球時刻 - Sourav-Ganguly-Mahendra-Singh-Dhoni如何獲取第一個「 - 」和第三個「 - 」之間的所有內容?

我只想抓取「V-CNHVNTNCHUUINP」。我寫的代碼不起作用:

$value = "www.abcd.com/Topic-V-CNHVNTNCHUUINP-Gangulys-waving-jersey-at-Lords-or-Dhonis-six-to-win-the-world-cup---Which-was-the-biggest-winning-moment-in-Indian-cricket-history-Sourav-Ganguly-Mahendra-Singh-Dhoni"; 

$newstr = substr($value, 0, strpos($value, '-', strpos($value, '-')+3)); 
$afterunderscore = substr($newstr, strpos($newstr, "-") + 1); 

這是取我:V-CNHVNTNCHUUINP。

但隨着鏈路進行測試時: www.abcd.com/Topic-HN-CNHVNTNCHWTSSW-Sharukh-Khan-or-Salman-Khan---Who-is-the-biggest-superstar-of-bollywood

我得到的結果是:HN。

目標:HN-CNHVNTNCHWTSSW當鏈接www.abcd.com/Topic-HN-CNHVNTNCHWTSSW-Sharukh-Khan-or-Salman-Khan---Who-is-the-biggest-巨星 - 寶萊塢的-

回答

2

這將如預期:

功能strposX將在$haystack返回$number的出現$needle的位置。然後只需使用substr來選擇存儲在$value變量中的想要的字符串部分。

function strposX($haystack, $needle, $number) { 
    preg_match_all("/$needle/", utf8_decode($haystack), $matches, PREG_OFFSET_CAPTURE); 
    return $matches[0][$number-1][1]; 
} 

$value = "www.abcd.com/Topic-HN-CNHVNTNCHWTSSW-Sharukh-Khan-or-Salman-Khan---Who-is-the-biggest-superstar-of-bollywood"; 

$start = min(strposX($value, '-', 1), strposX($value, '-', 3)); 
$length = abs(strposX($value, '-', 1) - strposX($value, '-', 3)); 

echo substr($value, $start + 1, $length - 1); 

輸出:

HN-CNHVNTNCHWTSSW 
2

你可以使用正則表達式拿到賽:

$value = "www.abcd.com/Topic-HN-CNHVNTNCHWTSSW-Sharukh-Khan-or-Salman-Khan---Who-is-the-biggest-superstar-of-bollywood"; 

// will account for "V-CNHVNTNCHUUINP" and "HN-CNHVNTNCHWTSSW" 
$pattern = "/Topic-([A-Z]+-[A-Z]+)-/"; 
$matches = []; 

preg_match($pattern, $value, $matches); 

if (isset($matches[1])) { 
    // we got a match 
    echo $matches[1]; // prints "HN-CNHVNTNCHWTSSW" 
} 
相關問題