I'm trying to replace the last occurence of a comma in a text with "and" using strrchr()
and str_replace()
.
Example:
$likes = 'Apple, Samsung, Microsoft';
$likes = str_replace(strrchr($likes, ','), ' and ', $likes);
But this replaces the entire last word (Microsoft in this case) including the last comma in this string. How can I just remove the last comma and replace it with " and " ?
I need to solve this using strrchr()
as a function. That's why this question is no duplicate and more specific.
just provide the answer with function strrchr()
$likes = 'Apple, Samsung, Microsoft';
$portion = strrchr($likes, ',');
$likes = str_replace($portion, (" and" . substr($portion, 1, -1)), $likes);
because strrchr()
will
This function returns the portion of string
See Doc here
so we just need only replace the comma symbol should be fine. and the comma will be always the first character when you use strrchr()
See Demo here
To replace only the last occurrence, I think the better way is:
$likes = 'Apple, Samsung, Microsoft';
$likes = substr_replace($likes, ' and', strrpos($likes, ','), 1);
strrpos finds the position of last comma, and substr_replace puts the desired string in that place replacing '1' characters in this case.
You can use regex to find last comma in string. Php preg_replace()
replace string with another string by regex pattern.
$likes = 'Apple, Samsung, Microsoft';
$likes = preg_replace("/,([^,]+)$/", " and $1", $likes)
Check result in demo
first, you gotta separate the elements into an array with all but the last one, and the last one. then you put them back together with commas and an "and", respectively
$likes = "A, B, C";
$likes_arr = explode(",", $likes);
$last = array_pop($likes_arr);
$likes = implode(",", $likes_arr) . " and" . $last;
echo $likes; //"A, B and C";
however: don't forget to check if you actually have enough elements. this fails for inputs without comma.