英文:
I want to validate my numbers with regex before using it but it not working out
问题
I want to validate my numbers with regex before using it but it not working out
I want the first digit to start with 0 follow by 2 or 5 and follow by 4 and the rest continue to 10 digit
<?php
$str = "0241310102";
$pattern = "([0]{1}[2,5]{1}[4]{1}[0-9]{7})";
if(preg_match($pattern, $str)){
echo "YES";
}else{
echo "NO";
}
?>
英文:
I want to validate my numbers with regex before using it but it not working out
I want the first digit to start with 0 follow by 2 or 5 and follow by 4 and the rest continue to 10 digit
<?php
$str = "0241310102";
$pattern = "([0]{1}[2,5]{1}[4]{1}[0-9]{7})";
if(preg_match($pattern, $str)){
echo "YES";
}else{
echo "NO";
}
?>
答案1
得分: 1
- 你需要将模式锚定到字符串的开头/结尾(
^
,$
)。 - 单个数字不需要被指定为字符类
[0]
→0
- 量词只需要在与1不同的情况下指定
0{1}
→0
[2,5]
会包含字符类中的逗号 →[25]
$examples = [
"0241310102",
"1241310102",
"0541310102",
"0551310102",
"0241"
];
$pattern = '(^0[25]4[0-9]{7}$)';
foreach ($examples as $example) {
echo $example, ": ";
if (preg_match($pattern, $example)) {
echo "YES", "\n";
} else {
echo "NO", "\n";
}
}
英文:
- You need to anchor the pattern to the start/end of the string (
^
,$
). - Single digits do not need to be specified as a character class
[0]
→0
- Quantifier need only to be specified if different from one
0{1}
→0
[2,5]
would include the comma in the character class →[25]
$examples = [
"0241310102",
"1241310102",
"0541310102",
"0551310102",
"0241"
];
$pattern = '(^0[25]4[0-9]{7}$)';
foreach ($examples as $example) {
echo $example, ": ";
if (preg_match($pattern, $example)) {
echo "YES", "\n";
} else {
echo "NO", "\n";
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论