简体   繁体   中英

preg_match if string contain + or -

How to validate if a string contain either + or - ??

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

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

output

Array
(
)
Array
(
)

正则表达式必须位于定界符之间:

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

You could do this without regex.

Use strpos() function.

$str = '+123-';

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

Hope this helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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