0

I want to check whether the search keyword 'cli' or 'ent' or 'cl' word exists in the string 'client' and case insensitive. I used the preg_match function with the pattern '\bclient\b'. but it is not showing the correct result. Match not found error getting.

Please anyone help

Thanks

Krishna Priya
  • 381
  • 1
  • 3
  • 7

3 Answers3

2

I wouldn't use regular expressions for this, it's extra overhead and complexity where a regular string function would suffice. Why not go with stripos() instead?

$str = 'client';
$terms = array('cli','ent','cl');
foreach($terms as $t) {
    if (stripos($str,$t) !== false) {
        echo "$t exists in $str";
        break;
    }
}
zombat
  • 92,731
  • 24
  • 156
  • 164
  • `strpos()/stripos()` are faster and more memory efficient than `strstr()/stristr()` if you just need to know whether a given substring exists. – zombat Jan 29 '10 at 06:15
  • echo stripos('client',$filterstr); it is showing 0 as result. when my search keyword ='cli' – Krishna Priya Jan 29 '10 at 06:16
  • Yes. If you read the documentation for `stripos()` you'll see that if returns the position index of the substring match, not the substring itself. If you want to output which term matched, just `echo $filterstring`. You didn't mention what kind of output you wanted in your function, just that you wanted to match a substring, so I assumed you were just looking for a true/false match. – zombat Jan 29 '10 at 06:19
  • Thanks for ur help and quick reply. I got the results using that function. Thanks again. $pos1 = stripos("client", $filterstr); if ($pos1 !== false) $flag=1; return $flag; – Krishna Priya Jan 29 '10 at 06:23
  • I agree, but `stripos` as oppsed to `strpos` gets slower the longer the strings become up to the extent where Regex *may* be faster. See a similar question and my benchmarks at http://stackoverflow.com/questions/1962031/how-to-check-if-a-string-starts-with-in-php/1962244#1962244 – Gordon Jan 29 '10 at 08:32
0

Try the pattern /cli?|ent/

Explanation:

cli matches the first part. The i? makes the i optional in the search.

| means or, and that matches cli, or ent.

CodeJoust
  • 3,760
  • 21
  • 23
0

\b is word boundary, It would not match cli in client, you need to remove \b

YOU
  • 120,166
  • 34
  • 186
  • 219