Search code examples
phpregexreplacespecial-charactersstring-formatting

I need help building a regular expression that will only leave behind letters and whitespace


I am building a form in PHP that requires that the field values only contain letters and whitespace(s).

There are a few small twists on this problem though:

  • I can't have more than one whitespace in a row
  • There can't be a leading or trailing whitespace in the string (The same effect of the TRIM() function)
  • The special characters and/or whitespaces that are non-conforming need to be replaced with a single whitespace

Examples of input & output:

INPUT
ConQueso, Cheese
OUTPUT
ConQueso Cheese

INPUT
0 Eddie Murphy-Washington, the 3rd .
OUTPUT
Eddie Murphy Washington the rd


Solution

  • Simply replace [^a-z]+ with space. And at the end, do a trim().

    $text = trim(preg_replace('/[^a-z]+/i', ' ', $text));