tags:

views:

33

answers:

3

Hi,

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

+2  A: 

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
Don't forget `strstr()`
alex
`strpos()/stripos()` are faster and more memory efficient than `strstr()/stristr()` if you just need to know whether a given substring exists.
zombat
echo stripos('client',$filterstr); it is showing 0 as result. when my search keyword ='cli'
Krishna Priya
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
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
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
A: 

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
A: 

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

S.Mark