Reputation: 161
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
Upvotes: 1
Views: 51
Reputation: 728
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
Upvotes: 2
Reputation: 13083
You could use regular expression to get the match:
$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"
}
Upvotes: 2