header('Content-Type: text/html; charset=utf-8');
$pattern='/[^0-9A-Za-z_]/';
$string='!$@!#%$#^##';
if(preg_match($pattern, $string,$match)){
echo 'Matched, the result is:' ;
var_dump($match);
}
else{
echo 'No match';
}
?>
Output: Matched, The result is: array(1) { [0]=> string(1) "!" }
I don’t understand that there are many in $string that are not within the range of [^0-9A-Za-z_] Why only one '!' is output?
preg_match() only matches once. If it matches content that meets the conditions, it will return immediately and will not continue to match, even if there are other content that meets the conditions later.
preg_match() only matches once. If it matches content that meets the conditions, it will no longer match. If you want to match all the content that meets the conditions, you can use preg_match_all($pattern, $string, $arr), $arr will save the match. All eligible content