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?
Advertisement
Answer
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