Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to replace last comma in string with "and" using php?

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.

like image 257
AlexioVay Avatar asked Jan 20 '17 11:01

AlexioVay


People also ask

How do I remove the last comma from a string using PHP?

To remove comma, you can replace. To replace, use str_replace() in PHP.

How do I remove the last comma from a string?

To remove the last comma from a string, call the replace() method with the following regular expression /,*$/ as the first parameter and an empty string as the second. The replace method will return a new string with the last comma removed. Copied!


2 Answers

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.

like image 145
Masteruniversal Avatar answered Nov 14 '22 07:11

Masteruniversal


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

like image 4
Mohammad Avatar answered Nov 14 '22 07:11

Mohammad