How can I replace a consecutive multiple space to a single space, and not allow space in the beginning and end of the string?
Here is my regex
preg_match("/^([-a-z_ ])+$/i", $str)
How can I replace a consecutive multiple space to a single space, and not allow space in the beginning and end of the string?
Here is my regex
preg_match("/^([-a-z_ ])+$/i", $str)
Nothing difficult here:
if (!preg_match('~\A\s|\s\z~', $str)) {
$str = preg_replace('~\s\s+~', ' ', $str);
} // else deny
If you want to check at the same time the string only contains ascii letters, underscores, hyphens or spaces with at least one character (as in your example), you can change the first pattern to:
if (!preg_match('~\A(?:\s|\z)|[^-a-z_\s]|\s\z~i', $str)) {