2016-04-09 149 views
0

如何驗證字符串是否包含+-preg_match如果字符串包含+或 -

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

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

輸出

Array 
(
) 
Array 
(
) 
+1

不需要在字符類中轉義'-'或'+' – rock321987

回答

2

正則表達式必須是分隔符之間:

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

你可以做到這一點沒有正則表達式。

使用strpos() function.

$str = '+123-'; 

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

希望這有助於。

相關問題