Remove words with comma at the end?

$string = "word1, word2, word3, word4"

How to remove from above all but word4?

With regex

$string = preg_replace('/([a-zA-Z0-9]+,)/gi', "", "word1, word2, word3, word4");

And if you want to get rid of that space after each comma, then use


1 Like

One way would go like

array_pop(explode(', ', $string));

More nuanced results could be achieved using regular expressions, e.g. if there may or may not be a space after the comma

array_pop(preg_split('/,\s?/', $string));

Ninja’d by @cpradio! :-)

1 Like

That works great. Please I have just noticed that some might contain numbers like this:

Toledo, Washington 98591, EE. UU.

There might be a space like this: Washington 98591,

Then you need to permit a space in the matching range


The matching range is the part within [ and ] Since Washington 98591 has a space before it hits a comma, it needs to have that space in the matching range.

Similarly, if you find some that have a . in it prior to the last word, you may need to allow that too using

Also, @m3g4p0p’s solution has less nuisances than the regex approach. With the approach I took, you have to whitelist everything you want it to ignore, with his, it will ignore everything and simply return the last set of words after the last comma. It may be better to use that approach depending on your ultimate goal.

1 Like

This one works: /([a-zA-Z0-9\s]+,\s?)/gi but how do I integrate it into preg_replace

It gives me errors: $str_Pattern = '/([a-zA-Z0-9\s]+,\s?)/gi';

preg_replace(): Unknown modifier ‘g’

Just remove the ‘g’, it isn’t necessary for PHP’s preg_replace function.

It’s not working if I remove g

What is your input, as when I ran it it did…

Toledo, Washington 98591, EE. UU.

Here is the code I produced

It has that input, and outputs EE. UU.

Yes thanks big time works great that is it thank you all guys!

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.