0

I've been trying to replace my second occurrence for a certain character
For Example: Hey, I'm trying something With PHP, Is it Working?
I need to get the position of the second comma, I've tried to use strpos but in vain because it's define that it finds the first occurrence of a string so I got Position: 3, any one knows a solution?

Matrix
  • 23
  • 5

2 Answers2

2

The strpos function accepts an optional third parameter which is an offset from which the search for the target string should begin. In this case, you may pass a call to strpos which finds the first index of comma, incremented by one, to find the second comma.

$input = "Hey, I'm trying something With PHP, Is it Working?";
echo strpos($input, ",", strpos($input, ",") + 1);  // prints 34

Just for completeness/fun, we could also use a regex substring based approach here, and match the substring up the second comma:

$input = "Hey, I'm trying something With PHP, Is it Working?";
preg_match("/^[^,]*,[^,]*,/", $input, $matches);
echo strlen($matches[0]) - 1;  // also prints 34
Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360
0

I know this has been already answered, but a more generic solution to find the last occurrence is to use strrpos.

strrpos accepts a third parameter that can be negative (contrary to strpos). If negative, the search is performed right to left skipping the last offset bytes of the haystack and searching for the first occurrence of needle.

$foo = "0123456789a123456789b123456789c";
// Looking for '7' right to left from the 5th byte from the end
var_dump(strrpos($foo, '7', -5));
Jon
  • 766
  • 1
  • 9
  • 27