开发者

PHP - Check if a text is containing a word

I want to check if my text contains one of words, probably from an array like:

$array = array('BIG','SMALL', 'NORMAL');

Example of what can contains my text variable: $text = "BEAUTIFUL BIG UMBRELLA..."; $text = "SMALL GREEN TEE-SHIRT";

I want to set a variable size; --> if my text contains the word BIG, I want to开发者_开发技巧 set the variable size='BIG'....

Thanks a lot.


The best way is with regular expressions, as bart and IVIR3zaM said. Here is an alternate usage:

<?php
$text = "This is a normal text where find words";
$words = array('BIG','SMALL','NORMAL');

// It would be a nice practice to preg_quote all your array items:
// foreach ( $words as $k => $word ) {
//  $words[$k] = preg_quote($word);
// }

$words = join("|", $words);
$matches = array();
if ( preg_match('/' . $words . '/i', $text, $matches) ){
    echo "Words matched:";
    print_r($matches);
}

You can check it working here http://ideone.com/LwSf3P

Remember to use the /i modifier to find matches non-case-sensitive.


Don't be afraid of regular expressions... Try

 if(preg_match('/\b(BIG|SMALL|NORMAL)\b/', $text, $matches)) ...

The \b is to make sure you indeed have an entire word; append "i" after the slash in the pattern if you want case insensitive match.


Use strpos to test for a single word:

if(strpos($text, $word) !== false) { /* $text contains $word */ }

http://php.net/strpos

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜