Search code examples
phpsubstrstrpos

How to fetch everything between the first "-" & third "-" in php?


I have a pretty url link: 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

I want to fetch only "V-CNHVNTNCHUUINP". The code which i wrote isn't working:

$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);  

This is fetching me : V-CNHVNTNCHUUINP.

But when testing with link: www.abcd.com/Topic-HN-CNHVNTNCHWTSSW-Sharukh-Khan-or-Salman-Khan---Who-is-the-biggest-superstar-of-bollywood

The result i get is: HN.

GOAL: Fetch HN-CNHVNTNCHWTSSW When link is www.abcd.com/Topic-HN-CNHVNTNCHWTSSW-Sharukh-Khan-or-Salman-Khan---Who-is-the-biggest-superstar-of-bollywood


Solution

  • This will work as expected:

    Function strposX will return position of $number appearance of $needle in $haystack. Then just use substr to select wanted part of string stored in $value variable.

    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);
    

    Output:

    HN-CNHVNTNCHWTSSW