简体   繁体   English

PHP preg_match? 如何返回不匹配的字符?

[英]PHP preg_match? How to return not matched characters?

Lets say i have: 可以说我有:

$string = 'qwe1ASD@';

if(preg_match('/^[a-zA-Z]+$/', $string))
{
    echo 'OK';
}
else
{
    echo 'BAD';
}

Now, is there simple solution, to find all characters from $string which don't match expression? 现在,有没有简单的解决方案,可以从$ string中查找与表达式不匹配的所有字符? So in return, in place of "BAD" i want to have ex. 因此,作为回报,我想代替“ BAD”。 "BAD. You can't use following characters: 1@" “糟糕。您不能使用以下字符:1 @”

Thanks in advance for any simple hints! 在此先感谢您提供任何简单提示! :) :)


Thank you Floern, your answer suit best my needs. 谢谢弗洛恩,您的回答最适合我的需求。 It have only one "preg" so it's also good for performance. 它只有一个“预浸料”,因此对性能也有好处。 Thank you again. 再次感谢你。 I implemented it for now as follw: 我现在以以下方式实现它:

if(preg_match_all('/[^a-zA-Z0-9]/s', $string, $forbidden))
{
    $forbidden = implode('', array_unique($forbidden[0]));

    echo 'BAD. Your string contains forbidden characters: '.htmlentities($forbidden).'';
}
$tmpstring=preg_replace('~[A-Za-z]~','',$string);
if(strlen($tmpstring))
    //bad chars: $tmpstring

You could use preg_match_all() : 您可以使用preg_match_all()

if(preg_match_all('/[^a-zA-Z]/s', $string, $matches)){
    var_dump($matches); // BAD
}
else{
    echo 'OK';
}
$string = 'qwe1ASD@';

if(preg_match('/^[a-zA-Z]+$/', $string))
{
    echo 'OK';
}
else
{
    echo 'BAD.  You cannot use the following characters: ' + preg_replace('/[a-zA-Z]/', '', $string);
}

There are different ways. 有不同的方式。 I find this one nice: 我觉得这很不错:

$check = preg_prelace('/[a-zA-Z]/', '', $string);

if ($check) echo 'BAD ' . $check;

UPDATE: 更新:

if (strlen($check)) echo 'BAD ' . $check;

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

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