Darien Fawkes Darien Fawkes - 7 months ago 12
PHP Question

How write regular expression extra?

I need a little help with using regular expression. I need check text consist only simbols, numbers and simbols _ - ( ) : , . ? / + * = « » % @ # $

I try:

if(preg_match("/^[А-Яа-яa-zA-Z0-9()-_«»%@#\s]+$/", $title) {
//success
} else {
//error
}


It not working.

Answer

You shoul fix the regex as

'/^[ёЁА-Яа-яa-zA-Z0-9()_«»%@#\s-]+$/'

You might also want to escape the hyphen if another "developer" may add up more symbols to the regex and ruin it (as Lashane mentions in the comment).

Two main points:

  • ё and Ё were missing from the а-яА-Я range
  • - between ) and _ created a range allowing all uppercase letters and some symbols:

enter image description here

See the regex demo.