Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP Preg_match match exact word

I have stored as |1|7|11| I need to use preg_match to check |7| is there or |11| is there etc, How do I do this?

like image 480
ITg Avatar asked Nov 28 '22 08:11

ITg


1 Answers

Use \b before and after the expression to match it as a whole word only:

$str1 = 'foo bar';       // has matches (foo, bar)
$str2 = 'barman foobar'; // no matches

$test1 = preg_match('/\b(foo|bar)\b/', $str1);
$test2 = preg_match('/\b(foo|bar)\b/', $str2);

var_dump($test1); // 1
var_dump($test2); // 0

So in your example, it would be:

$str1 = '|1|77|111|';  // has matches (1)
$str2 = '|01|77|111|'; // no matches

$test1 = preg_match('/\b(1|7|11)\b/', $str1);
$test2 = preg_match('/\b(1|7|11)\b/', $str2);

var_dump($test1); // 1
var_dump($test2); // 0
like image 93
netcoder Avatar answered Dec 06 '22 00:12

netcoder