preg_match特殊字符

ste*_*osn 10 php

如何使用preg_match查看[^'£$%^&*()}{@:'#~?><>,;@|\-=-_+-¬`]字符串中是否存在特殊字符?

小智 12

[\W]+ 将匹配任何非单词字符.

  • 通常,我会说`[\ W]`仍然很适合您,因为“文字字符”是指任何字母,数字或下划线,并且几乎不包含其他所有内容。我不确定是否包含连字符。然后我注意到下划线出现在您要检查的字符列表中。由于您只想查找单个字符,因此使用`explode()`和`in_array()`代替`preg_match()`可能会更快,或者只使用`while()`循环。尽管这些都不是非常直观的。 (2认同)

pmm*_*pmm 10

使用preg_match.此函数接受正则表达式(模式)和主题字符串,1如果匹配,0则返回,如果不匹配,或者false发生错误.

$input = 'foo';
$pattern = '/[\'\/~`\!@#\$%\^&\*\(\)_\-\+=\{\}\[\]\|;:"\<\>,\.\?\\\]/';

if (preg_match($pattern, $input)){
    // one or more matches occurred, i.e. a special character exists in $input
}
Run Code Online (Sandbox Code Playgroud)

您还可以为" 执行正则表达式匹配"功能指定标志和偏移量.请参阅上面的文档链接.


Dav*_*d D 7

我的功能让生活更轻松。

function has_specchar($x,$excludes=array()){
    if (is_array($excludes)&&!empty($excludes)) {
        foreach ($excludes as $exclude) {
            $x=str_replace($exclude,'',$x);        
        }    
    }    
    if (preg_match('/[^a-z0-9 ]+/i',$x)) {
        return true;        
    }
    return false;
}
Run Code Online (Sandbox Code Playgroud)

第二个参数 ($excludes) 可以与您希望忽略的值一起传递。

用法

$string = 'testing_123';
if (has_specchar($string)) { 
    // special characters found
} 

$string = 'testing_123';
$excludes = array('_');
if (has_specchar($string,$excludes)) { } // false
Run Code Online (Sandbox Code Playgroud)