Replace the last comma in a string using Regular Expression
Use greediness to achieve this:
$text = preg_replace('/(.*),/','$1 and',$text)
This matches everything to the last comma and replaces it through itself w/o the comma.
How to replace last comma in string with and using php?
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.
Remove last comma (and possible whitespaces after the last comma) from the end of a string
This will remove the last comma and any whitespace after it:
str = str.replace(/,\s*$/, "");
It uses a regular expression:
The
/
mark the beginning and end of the regular expressionThe
,
matches the commaThe
\s
means whitespace characters (space, tab, etc) and the*
means 0 or moreThe
$
at the end signifies the end of the string
Replace final comma in a string with and
You probably want
,(?=[^,]+$)
for example:
"1, 2, 3, 4".replace(/,(?=[^,]+$)/, ', and');
(?=[^,]+$)
checks that there are no more commas after this comma. (?!.*,)
would also work.
You can even check there isn't already an and
:
,(?!\s+and\b)(?=[^,]+$)
Working example: https://regex101.com/r/aE2fY7/2
Replace last comma separated value by another using regex
You can use replace()
with regex /,[^,]+$/
to match the last string
var str = "a,b,c,d,e,old";var res = str.replace(/,[^,]+$/, ",new");// or you can just use// var res = str.replace(/[^,]+$/, "new");document.write(res);
Replace last instance of comma with 'and' in a string
I think the replaceFirst
is better than replaceAll
for you because you want to replace only once not all, and it run faster than replaceAll
.
using
${number}
to capturing groups."a, b, c".replaceFirst(",([^,]+)$", " and$1"); // return "a, b and c"
using positive lookahead:
"a, b, c".replaceFirst(",(?=[^,]+$)", " and"); // return "a, b and c"
How to remove the last comma from each line in a string?
This is not too good in terms of performance if your string is very long, but it should do
"\n".join(x[:-1] for x in output.splitlines())
Related Topics
Get Last Word from Url After a Slash in PHP
In PHP How to Access a ":Private" Array in an Object
Is It Acceptable to Use a Mix of Object Oriented Style with Procedural Style in Coding PHP
Converting a Carbon Date to MySQL Timestamp
Move Value in PHP Array to the Beginning of the Array
How to Run PHP Code from File_Get_Contents or File in a Function
How to Curry Method Calls in PHP
Using PHP Replace Regex with Regex
Why Are PHP's MySQL_ Functions Deprecated
How to Send Https Posts Using PHP
Upload File with PHP and Save Path to SQL
Count Word Frequency in a Text
How to Validate Non-English (Utf-8) Encoded Email Address in JavaScript and PHP
Get Values Stdclass Object PHP