Simply replace [^a-z]+
with space. And at the end, do a trim()
.
$text = trim(preg_replace('/[^a-z]+/i', ' ', $text));
题
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:
TRIM()
function)Examples of input & output:
INPUTConQueso, Cheese
OUTPUTConQueso Cheese
INPUT0 Eddie Murphy-Washington, the 3rd .
OUTPUTEddie Murphy Washington the rd
解决方案
Simply replace [^a-z]+
with space. And at the end, do a trim()
.
$text = trim(preg_replace('/[^a-z]+/i', ' ', $text));
其他提示
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));