How can I allow single underscores only with preg_match?
The regex I made below takes double underscores which is not I want…
if(!preg_match('/^[a-z0-9\s\_]+$/', $name))
{
$error = true;
echo '<error elementid="name" message="name - please use alpha-numbers and lowercaps only." />';
}
For instance,
hello world ok
hello_world ok
hello__world not ok
hello_world__again__ not ok
_hello_world_again_ not ok
Including the
_inside[]+allows for multiples. You need to surround it in[]+but not include it inside. The entire structure is surrounded by()+to allow for multiples of it, but it always ends with letters, numbers, or spaces.Breaking it down:
()+allows for multiples of the whole structure[a-z0-9\s]+Multiple letters, numbers, spaces (not underscore_?[a-z0-9]+optional single underscore inside the multiple letters/numbers/spaces, but not followed by space[a-z0-9\s]+more letters, numbers, spaces at the end (can’t end in underscore)/iCase insensitive (remove theiif you need case sensitivity)