简体   繁体   English

仅允许使用preg_match的几个字符

[英]Allow only few characters with preg_match

I want to use preg_match to allow only few characters, more exactly, I want to allow only these characters: az AZ 0-9 . 我想使用preg_match只允许几个字符,更确切地说,我只允许这些字符:az AZ 0-9。 , ( ) @ # ! ,()@#! ?

How can I do that with preg_replace, to check if text contains more than these characters or not? 如何使用preg_replace进行操作,以检查文本是否包含超过这些字符的文字?

In order to test if your sting contains invalid characters, you could do: 为了测试您的字符串是否包含无效字符,您可以执行以下操作:

if ( preg_match('/[^a-zA-Z0-9.,()@#!?]/', $string) )
    echo 'At least ONE invalid character found!';

I'm not sure I well understand what you want, but here are some regex that you can use: 我不确定我是否了解您想要什么,但是这里有一些可以使用的正则表达式:

if ( preg_match('/^[^a-zA-Z0-9.,()@#!?]+$/', $string) )
    echo 'All characters are invalid!';

if ( preg_match('/^[a-zA-Z0-9.,()@#!?]+$/', $string) )
    echo 'All characters are valid!';

如果要删除字符串中除指示字符外的所有字符,可以使用:

$sanitized = preg_replace('/[^a-zA-Z0-9\.\,\(\)@#!?]/', '', $string);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM