Regex for any English ASCII character, including special characters

I want to write a regular expression in php to match only any English characters, spaces, numbers and all special characters.

From this question regex any ascii character

I tried this

preg_match("/[\x00-\x7F]+/", $str); 

but he gives a warning

 No ending delimiter '/' found 

so how to write this regular expression in php.

the alternative would be the same as [az \ d \ s], and also take into account all the special characters one by one, but there is no way to make it easier?

thanks

+8
php regex preg-match
source share
2 answers

There are a number of complex solutions, but I would suggest this beautifully simple regular expression:

 ^[ -~]+$ 

It allows all printable characters in an ASCII table.

In PHP:

 $regex = '%^[ -~]+$%'; if (preg_match($regex, $yourstring, $m)) { $thematch = $m[0]; } else { // no match... } 

Explanation

  • Anchor ^ states that we are at the beginning of the line
  • The character class [ -~] matches all characters between space and tilde (all printable characters in the ASCII table)
  • The quantization coefficient + means "corresponds to one or more of them"
  • The $ anchor states that we are at the end of the line
+14
source share

PHP regex comes with a set of character classes that you can reference, and ascii is one of them

 $test = "hello world 123 %#* 单 456"; preg_match_all("/[[:ascii:]]+/",$test,$matches); print_r($matches); 
+3
source share

All Articles