如何获取第一个“ - ”和&之间的所有内容在PHP中第三个“ - ”?

时间:2017-03-02 11:50:25

标签: php substr strpos

我有一个漂亮的网址链接: www.abcd.com/Topic-V-CNHVNTNCHUUINP-Gangulys-waving-jersey-at-Lords-or-Dhonis-six-to-win-the-world-cup ---这,是最最大-winning矩功能于印度板球历史Sourav,甘古利 - 马亨德拉 - 辛格 - 纵帆船

我想只获取“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 ---谁是最最大-巨星的-宝莱

我得到的结果是:HN。

目标获取 HN-CNHVNTNCHWTSSW 当链接 www.abcd.com/Topic-HN-CNHVNTNCHWTSSW-Sharukh-Khan-or-Salman-Khan ---谁是最最大-巨星的-宝莱

2 个答案:

答案 0 :(得分: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"
}

答案 1 :(得分:2)

这将按预期工作:

功能strposX将在$number中返回$needle $haystack外观的位置。然后只需使用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