简体   繁体   English

快速php正则表达式问题(包括代码)

[英]Quick php Regex question (code included)

$first = ".";
$last = "a";
$middle= "testing-123.test";

if (preg_match("[a-zA-Z0-9]", $first)){
 echo 'Frist Returned valid.';
}
if (preg_match("[a-zA-Z0-9.-]", $middle)){
 echo 'Middle Returned valid.';
}
if (preg_match("[a-zA-Z0-9]", $last)){
 echo 'Last Returned valid.';
}

I am breaking down a string into 3 parts using substr so in this example the original text was ".testing-123.testa". 我正在使用substr将字符串分解为3个部分,因此在此示例中,原始文本为“.testing-123.testa”。 I didnt include the substr here but just predefined the variables in this case. 我没有在这里包含substr,但在这种情况下只是预定义了变量。 I want to check so it means the following requirements: 我想检查一下,这意味着以下要求:

First character: az, AZ, 0-9 NO SYMBOLS 第一个字符:az,AZ,0-9 NO SYMBOLS

middle character: az, AZ, 0-9, only . 中间字符:az,AZ,0-9,仅。 and - symbols 和 - 符号

Last character: same as first character. 最后一个字符:与第一个字符相同。

When I ran above code it echo'd nothing. 当我跑到上面的代码时,它什么也没回应。 Any ideas? 有任何想法吗?

You are missing delimitters, try adding / around your regex: 你缺少分隔符,尝试添加/围绕你的正则表达式:

if (preg_match("/[a-zA-Z0-9]/", $first)){
 echo 'Frist Returned valid.';
}
if (preg_match("/[a-zA-Z0-9.-]/", $middle)){
 echo 'Middle Returned valid.';
}
if (preg_match("/[a-zA-Z0-9]/", $last)){
 echo 'Last Returned valid.';
}

You might also want to use preg_match_all to find more/all instances. 您可能还想使用preg_match_all来查找更多/所有实例。

if (preg_match("/^[a-z0-9]+$/i", $first)){
 echo 'First Returned valid.';
}
if (preg_match("/^[a-z0-9.-]+$/i", $middle)){
 echo 'Middle Returned valid.';
}
if (preg_match("/^[a-z0-9]+$/i", $last)){
 echo 'Last Returned valid.';
}

should do what you need. 应该做你需要的。

You need delimiters ( / ), and you need to make sure that all characters are tested from the beginning to the end of the string ( ^ and $ anchors). 您需要分隔符( / ),并且需要确保从字符串的开头到结尾测试所有字符( ^$ anchors)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM