There is such a line. Всем привет 123 - this is the right one.

There is also such a string Hello world 78 - this is also the correct string.

And there is such a line. Как дела // is already a wrong line.

All these lines are written to a variable such as $text .

How can I use preg_match to check the variable $text for the presence of Latin or Russian letters and numbers?

Rummaged on the Internet and gathered here is, but it does not work.

 preg_match('/[a-z0-9]+/i',$text) 

Help make up the expression.

3 answers 3

 preg_match("/^[a-zа-яё\d]{1}[a-zа-яё\d\s]*[a-zа-яё\d]{1}$/i", $text); 

I explain what is written here:

  1. ^ - beginning of line
  2. [a-zа-яё\d]{1} - a string can begin with letters of the Latin or Russian language ( a-zа-яё ) or numbers ( \d ). One of these characters must be met {1} times. The group of characters consists in [ and ] .
  3. [a-zа-яё\d\s]* is the same as in the previous case, but we add any whitespace character (space, new line, tab). One of these characters can occur any number of times, 0 or more, which means * .
  4. [a-zа-яё\d]{1} - which character should be immediately before the end of the line.
  5. $ - actually, the end of the line.
  6. All this is enclosed in special limiters (dividers). They can be any character. It is better to use the slash. /здесь регулярное выражение/
  7. i - means that the regular expression is case-insensitive. It is indicated immediately after the delimiter and is called a flag.

Useful links:

  1. An article about regular expressions.
  2. The principle of the function preg_match
  • Thanks for the detailed explanation, I even saved it on my computer - Anatoly
  • But I did it the same way if (preg_match ("/ [^ (\ w) | (\ x7F- \ xFF) | (\ s)] /", $ text)) {echo "The name can contain only Russian / lat . characters, space, numbers and _ "; } - Anatoly
  • when you understand the meaning - it is a pleasure to write code;) - Razzwan
  • @Razzwan, have unicode already been canceled? And {1} extra here. - Visman
  • @Visman, you can correct - write correctly. I do not know what needs to be changed to make it right and why. - Razzwan

The answer I was looking for

 if (preg_match("/[^(\w)|(\x7F-\xFF)|(\s)]/",$text)) { echo "Имя может содержать только русс. / лат. символы, пробел, цифры и знак _"; } else { echo "Этот зголовок - $text нормальный"; } 

    Php already has a function that does it.

     bool ctype_alnum ( string $text ) 

    More information about the function by reference .