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?
Asked
Active
Viewed 675 times
0

Matrix
- 23
- 5
-
1Does this answer your question? [find the second occurrence of a char in a string php](https://stackoverflow.com/questions/13492759/find-the-second-occurrence-of-a-char-in-a-string-php) – El_Vanja Dec 18 '20 at 10:32
-
Nope, It uses regex and don't prefer it – Matrix Dec 18 '20 at 10:37
-
1The second one uses `strpos`. – El_Vanja Dec 18 '20 at 10:39
2 Answers
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