如何检查字符串是否包含方括号php

时间:2017-05-24 09:46:27

标签: 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))

感谢您的帮助。感谢。

4 个答案:

答案 0 :(得分:2)

您应该在表达式中添加转义方括号。

preg_match('/[\'^£$%&*()}{@#~?><>,|=_+¬-\[\]]/', $string)
编辑:向@Thamilan道歉,我没有看到你的评论。

编辑2:您也可以使用preg_quote功能。

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

preg_quote函数将为您转义特殊字符。

答案 1 :(得分:1)

使用strpos:

$string = 'starw]ars';

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

有关其他信息,请参阅以下答案: How do I check if a string contains a specific word in PHP?

答案 2 :(得分: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';
}

答案 3 :(得分:0)

试试这个例子:

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

<强>输出:

输出:包含特殊字符

相关问题