0
$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 ?

deceze
  • 510,633
  • 85
  • 743
  • 889
dtsky
  • 13
  • 1
  • *"why is the result returned 6666"* — Because `strpos` *"[finds] the position of the first occurrence of a substring in a string"*. What else did you expect it to do?! – deceze Mar 10 '22 at 09:06
  • 3
    You should look into `parse_url`: https://www.php.net/manual/en/function.parse-url.php – Angelin Calu Mar 10 '22 at 09:06
  • `https://www.php.net/manual/de/function.strpos.php` – Refugnic Eternium Mar 10 '22 at 09:06
  • 1
    The second argument is the character offset, this means from which character it should start looking. I think you are trying to use the second argument as "get the nth encounter of '/'` which is not supported. – MaartenDev Mar 10 '22 at 09:06
  • From the manual: `Returns 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. Returns false if the needle was not found.` As such, it always finds the position of the first slash, which just happens to be at index '6'. – Refugnic Eternium Mar 10 '22 at 09:07
  • @Angelin Calu I tried parse_ url,there are other problems when the URL contains ports – dtsky Mar 10 '22 at 09:11
  • You just need to remember that `PHP_URL_PORT`. I believe that's what you encountered in regards to having ports.... – Angelin Calu Mar 10 '22 at 09:13
  • 1
    This is an XY Problem. You should use a more appropriate tool for this task. – mickmackusa Mar 10 '22 at 10:04

1 Answers1

1

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

iLittleWizard
  • 385
  • 2
  • 12
  • thx , i got it , the first time I saw this parameter, I understood it with some deviation – dtsky Mar 10 '22 at 09:20