php - Using preg_match many time to check if strings are in text -
i have text text area, contains 4 necessary strings. before insert text on database check presence of strings.
is there better , alternative way 4 preg_match
operations, maybe using preg_match_all
?
if i'd replace 4 strings
else, difference between preg_replace
, str_replace
. should use?
here code:
if(isset($_post['text'])){ $text= $link->real_escape_string($_post['text']); $string = $text; $pattern1 = '/limite_type/'; $pattern2 = '/limite_set/'; $pattern3 = '/today_price/'; $pattern4 = '/auto_sign/'; if(preg_match($pattern1, $string) && preg_match($pattern2, $string) && preg_match($pattern3, $string) && preg_match($pattern4, $string)) { echo 'ok'; }else{ echo 'not found'; } die(); }
if want check presence of exact words, don't need use regex, use strpos
instead faster:
$word1 = 'limite_type'; $word2 = 'limite_set'; $word3 = 'today_price'; $word4 = 'auto_sign'; if ( (strpos($string, $word1) && strpos($string, $word2) && strpos($string, $word3) && strpos($string, $word4))!==false) {
but if need patterns (with regex features inside):
$patterns = array('~\blimite_type\b~', '~\blimite_set\b~', '~\btoday_price\b~', '~\bauto_sign\b~'); $found = true; foreach($pattern $pattern) { if (!preg_match($pattern, $string)) { $found = false; break; } } echo ($found)? 'ok' : 'not found';
the advantage of these codes tests stop @ first false result.
Comments
Post a Comment