如何编写PHP preg_match正则表达式验证指定字符组成的字符串
Solution for Your preg_match Validation Requirement
Hey there! Let's get that regex sorted so your PHP form validation works exactly as you need it to.
First, let's recap what you need to allow in the string:
- Uppercase and lowercase letters
- Numbers
- Space
- Specific punctuation: comma (
,)、period (.)、plus (+)、hyphen (-)、exclamation mark (!)、colon (:)、semicolon (;)、parentheses (())
The Correct Regex Pattern
For PHP's preg_match, you need to wrap your pattern in delimiters (we'll use / here) and handle special characters properly. The hyphen (-) needs extra care—either place it at the start/end of the character set or escape it with a backslash so it's treated as a literal, not a range indicator.
Here's the pattern you should assign to $regex:
$regex = "/^[A-Za-z0-9 ,.+!:;()\-]+$/";
Let's Break Down the Pattern
/: Opening delimiter for the regex (required bypreg_match)^: Anchors the match to the start of the string[A-Za-z0-9 ,.+!:;()\-]: Character set containing all allowed characters:A-Za-z: All uppercase and lowercase letters0-9: All digits: Space character,.+!:;(): The allowed punctuation marks (none need escaping inside the character set except the hyphen)\-: Escaped hyphen to ensure it's treated as a literal character
+: Ensures there's at least one allowed character (swap this for*if you want to permit empty strings)$: Anchors the match to the end of the string (critical—this guarantees the entire string only uses allowed characters, not just that allowed characters exist somewhere in it)/: Closing delimiter
Modified Working Code
Here's your full code with the correct regex integrated:
<?php $regex = "/^[A-Za-z0-9 ,.+!:;()\-]+$/"; $string = "some user input in a form passed via POST to form processor"; if (preg_match($regex, $string)) { echo "Found a match!"; } else { echo "The regex pattern did not match."; } ?>
Quick Tips
- If empty strings should be allowed, change the
+to*in the pattern:/^[A-Za-z0-9 ,.+!:;()\-]*$/ - For stricter error handling, note that
preg_matchreturns1for a match,0for no match, andfalseif there's a regex error. You could adjust the condition topreg_match($regex, $string) === 1to avoid mistaking errors for "no match".
内容的提问来源于stack exchange,提问作者Fran_3
相关产品推荐
相关产品推荐

