Pergunta

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

Foi útil?

Solução

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

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

Outras dicas

Because it seems that you want to build a form for personal data input, you should use [^\pL] instead of [^A-Za-z], because there can be non ASCII letters (like ä or É) in names. (Additionally to the trim function, as descripted so far.)

Try this -

$text = "Some text here.";
$str = trim(preg_replace('/[^a-zA-Z\']/', ' ', $text));
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top