Jump to content


Check out our Community Blogs

Register and join over 40,000 other developers!


Recent Status Updates

View All Updates

Photo
- - - - -

Include a specific error, task, problem, or question in your title

strpos

This topic has been archived. This means that you cannot reply to this topic.
No replies to this topic

#1 uniqueideaman

uniqueideaman

    CC Resident

  • Advanced Member
  • PipPipPipPip
  • 57 posts

Posted 26 April 2017 - 03:59 PM

Hiya,
 
 
On the above link, it is stated:
 
PHP Code:
$numberedString = "1234567890"; // 10 numbers from 1 to 0
 
$fivePos = strpos($numberedString, "5");
echo "The position of 5 in our string was $fivePos";
Display:
The position of 5 in our string was 4
Notice that the position is 4, which may seem confusing at first, until you realize that PHP starts counting from 0.
 
The number 1 - Position 0 - No match
The number 2 - Position 1 - No match
The number 3 - Position 2 - No match
The number 4 - Position 3 - No match
The number 5 - Position 4 - Match
Although we only searched for a single character, you can use this function to search for a string with any number of characters. Also, it is important to note that this function will return the position of the start of the first match. So if we had searched the same string for "567890" we would again find a match and position 4 because that is where the match starts.
 
I do not understand the last part and so can someone show an example:
So if we had searched the same string for "567890" we would again find a match and position 4 because that is where the match starts.

Oh, I now understand. It meant the string "567890" starts from position 4.

On previous example, it was searching for the single character 4's position. This time, it is searching where the string starts.

 

Ok. I understand that with strpos, you can only find the first match of a character or string but not any further than that if there were more than one match. And to fix this, I can use the incrementer to set the next starting point. Like so:

 
$numberedString = "1234567890123456789012345678901234567890";
 
$fivePos = strpos($numberedString, "5");
echo "The position of 5 in our string was $fivePos";
$fivePos2 = strpos($numberedString, "5", $fivePos + 1);
echo "<br />The position of the second 5 was $fivePos2";
 
So, naturally strpos has 2 parameters if you want to find the pos of only one match or the first match. Right ?
And, if you want to find all the matches' positions then you add the final matched position on the 3rd parameter. Right ?

Edited by uniqueideaman, 26 April 2017 - 03:59 PM.