PHP preg_match正则匹配问题:添加斜杠后无法正常运行
alpha_dash_space Function Hey there! The problem you're running into is super common with regular expressions in PHP—let's break it down and fix it quickly.
Why Adding a Slash Breaks Things
Your regex uses forward slashes (/) as delimiters (the characters that wrap the regex pattern). When you add an unescaped / inside the pattern, PHP thinks you're closing the regex early, which causes a syntax error. That's why your function stops working!
Two Easy Solutions
1. Escape the Slash with a Backslash
The simplest fix is to escape the slash you want to match by adding a backslash before it (\/). This tells PHP to treat it as a literal character instead of a delimiter.
Here's your updated function:
public function alpha_dash_space($str) { return ( ! preg_match("/^([-a-z0-9_\n\r%$#., \/])+$/i", $str)) ? FALSE : TRUE; }
2. Use a Different Delimiter
If you don't want to deal with escaping slashes, you can switch to a different delimiter that doesn't appear in your pattern. Common choices are #, ~, or |. For example, using # as the delimiter lets you include / directly without escaping:
public function alpha_dash_space($str) { return ( ! preg_match("#^([-a-z0-9_\n\r%$#., /])+$#i", $str)) ? FALSE : TRUE; }
Note: If you use # as a delimiter, you don't need to escape the # inside your character class—PHP handles that automatically when it's inside [].
Either approach will work perfectly. The first method is more standard, while the second can make your regex cleaner if you have lots of slashes to match.
内容的提问来源于stack exchange,提问作者Harun Anwar

