2017-05-24 163 views
1

我有一个奇怪的问题,也许你可以帮助我。我试图检查给定的字符串是否包含特殊字符。下面的代码正在工作,但是一个角色似乎在方括号[]的条件下得到了豁免。你能帮助我吗?谢谢。如何检查字符串是否包含方括号php

$string = 'starw]ars'; 

    if (preg_match('/[\'^£$%&*()}{@#~?><>,|=_+¬-]/', $string)) { 
     echo 'Output: Contains Special Characters'; 
    }else{ 
     echo 'Output: valid characters'; 
    } 

请注意:因为我需要接受其他语言的其他字符,如阿拉伯语,中国等,所以这意味着我需要指定不允许所有的字符,我不能低于使用条件。

if (!preg_match('/[^A-Za-z0-9]/', $string)) 

感谢您的帮助。谢谢。

+2

加入他们反斜杠'逃逸\ [\]' ,''/ [\'^ $ $%&*()} {@#〜?><>,​​| = _ +¬ - \ [\]] /'' – Thamilan

回答

1

你忘了在你的表达式添加括号[]。我已在您当前的表达式中添加此\[\]

Try this code snippet here

<?php 

ini_set('display_errors', 1); 

$string = 'starw]ars'; 

if (preg_match('/[\[\]\'^£$%&*()}{@#~?><>,|=_+¬-]/', $string)) 
{ 
    echo 'Output: Contains Special Characters'; 
} else 
{ 
    echo 'Output: valid characters'; 
} 
+1

这工作。谢谢:) –

2

您应该为表达式添加转义的方括号。

preg_match('/[\'^£$%&*()}{@#~?><>,|=_+¬-\[\]]/', $string) 

编辑:对@Thamilan道歉,我没有看到您的评论。

编辑2:你也可以使用preg_quote函数。

preg_match(preg_quote('\'^£$%&*()}{@#~?><>,|=_+¬-[]', '/'), $string); 

preg_quote函数将为您逃脱您的特殊字符。

1

使用strpos:

$string = 'starw]ars'; 

if (strpos($string, ']') !== false) { 
    echo 'true'; 
} 

欲了解更多信息如下回答: How do I check if a string contains a specific word in PHP?

+0

只搜索']'好的答案,但OP问“我试图检查给定的字符串是否包含特殊字符。下面的代码正在工作,但是一个字符似乎在方括号[]的条件下得到了豁免。“ –

0

试试这个例子:

<?php 
$string = 'starw]]$%ars'; 
if (preg_match('/[\'\/~`\[email protected]#\$%\^&\*\(\)_\-\+=\{\}\[\]\|;:"\<\>,\.\?\\\]/', $string)) 
{ 
    echo 'Output: Contains Special Characters'; 
} else 
{ 
    echo 'Output: valid characters'; 
} 
?> 

输出:

输出:包含特殊字符

相关问题