KDX KDX - 8 months ago 26
PHP Question

How to match alphanumeric and symbols using PHP?

I'm working with text content in UTF8 encoding stored in variable


, how do I append an extra space if the
string is ending with:

  • upper/lower case character

  • digit

  • symbol, eg.


This should do the trick:

preg_replace('/^(.*[\w?!])$/', "$1 ", $string);

In essence what it does is if the string ends in one of your unwanted characters it appends a single space.

If the string doesn't match the pattern, then preg_replace() returns the original string - so you're still good.

If you need to expand your list of unwanted endings you can just add them into the character block [\w?!]