如何用PHP检查字符串仅包含任意语言的字母、数字和空格?
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
umodifier 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

