You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何编写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 by preg_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 letters
    • 0-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_match returns 1 for a match, 0 for no match, and false if there's a regex error. You could adjust the condition to preg_match($regex, $string) === 1 to avoid mistaking errors for "no match".

内容的提问来源于stack exchange,提问作者Fran_3

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 03:22:34