If I need a string to match this pattern: " *- -***","123-12-123","123-1", how would I check the string to make sure it fits that, in PHP?
I want to make sure the string fits any of these patterns:
"***-**-***"
"123-12-123" (ONLY NUMERIC WITH -)
"123-1" (ONLY NUMERIC WITH -)
You can use the regex
/\d{3}\-\d(\d\-\d{3}|)/
If you need to match only that string, put ^
after the first /
and $
before the last /
Keep in mind this will match anything that starts ddd-d
as-is
You can see it work here https://3v4l.org/JI5GT
u can find all numbers without regex for example
$numbers=sscanf('123-12-123','%d-%d-%d');
print_r($numbers);
output
Array
(
[0] => 123
[1] => 12
[2] => 123
)
if you want get it with regex you can do with follow code
$re = '/\d{3}-\d{2}-\d{3}/m';
$str = '123-12-123';
preg_match_all($re, $str, $matches, PREG_SET_ORDER, 0);
// Print the entire match result
var_dump($matches);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.