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

如何用PHP检查字符串仅包含任意语言的字母、数字和空格?

Fixing Your Unicode String Validation Issue

Got it, let's get to the bottom of why those special characters (-*/) are slipping through your checks! The problem with your current code is that you're only verifying if the string contains at least one letter or number—you aren't making sure every single character falls into your allowed set (letters, numbers, spaces).

Here's the corrected approach: use a single regex that checks the entire string, ensuring all characters are either Unicode letters, Unicode numbers, or spaces. We'll use anchors to cover the full string and the u modifier to handle Unicode properly.

For strings that require at least one valid character:

if (preg_match("/^[\p{L}\p{N} ]+$/u", $string)) {
    // String is valid (only letters, numbers, spaces)
} else {
    // String has invalid characters like -, *, /, etc.
}

If you want to allow empty strings too:

Replace the + with * to match zero or more valid characters:

if (preg_match("/^[\p{L}\p{N} ]*$/u", $string)) {
    // Valid (includes empty strings)
}

Let's break down the regex components:

  • ^ marks the start of the string
  • [\p{L}\p{N} ] defines our allowed character set: any Unicode letter (\p{L}), any Unicode number (\p{N}), or a space
  • + means "one or more" of these allowed characters (use * for "zero or more")
  • $ marks the end of the string
  • The u modifier is critical—it tells PHP to process the string as Unicode, which is required for \p{L} and \p{N} to work across all languages.

Your original separate preg_match calls only checked if there was at least one letter or number present, but didn't block other characters. This new regex ensures there are no invalid characters anywhere in the string.

内容的提问来源于stack exchange,提问作者Ali Güzel

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.08 22:48:12