preg_match如果字符串包含+或 -

时间:2016-04-09 12:26:59

标签: php regex preg-match

如何验证字符串是否包含+- ??

preg_match('[\-\+]', '(292+3)*1', $match);
print_r($match);

preg_match('[\-\+]', '(292-3)*1', $match);
print_r($match);

输出

Array
(
)
Array
(
)

2 个答案:

答案 0 :(得分:2)

正则表达式必须在分隔符之间:

preg_match('/[-+]/', '(292+3)*1', $match);

答案 1 :(得分:2)

你可以在没有正则表达式的情况下做到这一点。

使用strpos() function.

$str = '+123-';

if (strpos($str, '+') !== FALSE || strpos($str, '-') !== FALSE) {
     echo 'Found it';
} else {
     echo 'Not found.';
}

希望这有帮助。