KDX KDX - 4 months ago 11
PHP Question

How to match alphanumeric and symbols using PHP?

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

$title
.

Using
preg_replace
, how do I append an extra space if the
$title
string is ending with:


  • upper/lower case character

  • digit

  • symbol, eg.
    ?
    or
    !


Answer

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?!]