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

PHP preg_match正则匹配问题:添加斜杠后无法正常运行

Fixing the Regex Issue When Adding a Slash to Your 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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 03:47:23