I want to write a regex in php to match only any english characters, spaces, numbers and all special chars.
From this question Regex any ascii character
I tried this
preg_match("/[\x00-\x7F]+/", $str);
but it throws a warning
No ending delimiter '/' found
so, how to write this regex in php.
the alternative would be smth like [a-z\d\s] and also one by one consider all special chars, but is not there a way to do simpler ?
Thanks
You can use this regex /^[ A-Za-z0-9_@./#&+-]*$/.
The regular expression represents all printable ASCII characters. ASCII code is the numerical representation of all the characters and the ASCII table extends from char NUL (Null) to DEL . The printable characters extend from CODE 32 (SPACE) to CODE 126 (TILDE[~]) .
[] denotes a character class. () denotes a capturing group. [a-z0-9] -- One character that is in the range of a-z OR 0-9.
Basically (0+1)* mathes any sequence of ones and zeroes. So, in your example (0+1)*1(0+1)* should match any sequence that has 1. It would not match 000 , but it would match 010 , 1 , 111 etc. (0+1) means 0 OR 1.
There are a number of intricate solutions, but I would suggest this beautifully simple regex:
^[ -~]+$
It allows all printable characters in the ASCII table.
In PHP:
$regex = '%^[ -~]+$%';
if (preg_match($regex, $yourstring, $m)) {
$thematch = $m[0];
}
else { // no match...
}
Explanation
^
anchor asserts that we are at the beginning of the string[ -~]
matches all characters between the space and the tilde (all the printable characters in the ASCII table)+
quantifier means "match one or more of those"$
anchor asserts that we are at the end of the stringPHP's regex comes with a set of character classes you can reference, ascii being one of them
$test = "hello world 123 %#* 单 456";
preg_match_all("/[[:ascii:]]+/",$test,$matches);
print_r($matches);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With