Wednesday, March 16, 2022

[FIXED] php strpos does not support slashes or symbols?

Issue

$str = 'https://example.com/tools/onphp.html';

echo strpos($str,'/',0);  //return 6

echo strpos($str,'/',1);  //return 6

echo strpos($str,'/',2);  //return 6

echo strpos($str,'/',3);  //return 6

in php 7.3

why is the result returned 6666

i want get result is 'https://www.example.com/' use substr($str,0,strpos($str,'/',2));

but it can not working

now i'm use

preg_replace('/^([\s\S]*?)\/\/([\s\S]*?)\/([\s\S]*?)$/','\1//\2',$str);

so is there a simpler solution ?


Solution

According to the PHP docs:

strpos(string $haystack, mixed $needle, int $offset = 0): int

offset: If specified, search will start this number of characters counted from the beginning of the string. If the offset is negative, the search will start this number of characters counted from the end of the string.

return: the position of where the needle exists relative to the beginning of the haystack string (independent of offset). Also note that string positions start at 0, and not 1.

When you are calling strpos('https://example.com/tools/onphp.html','/',3), the search starts from the character at index 3, which is 'p'

// start - |
strpos('https://example.com/tools/onphp.html', '/', 0); //returns 6

If you are trying to find the nth occurence of a string, you can refer to this question



Answered By - iLittleWizard

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.