0

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.

2
  • What will happen to BIGGIE SMALLS MID-SIZED RED T-SHIRT? Or more generally, what should happen on the occurrence of multiple keywords in a sentence? Commented Feb 14, 2011 at 10:39
  • The text come from a csv file and contains only one occurence. Commented Feb 14, 2011 at 10:45

3 Answers 3

3

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.

Sign up to request clarification or add additional context in comments.

Comments

2

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.

Comments

1

Use strpos to test for a single word:

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

http://php.net/strpos

2 Comments

$word can not be an array here ! And I want to use it like an array, any solution to test for multiple words ?
@Bizboss there are loops to handle arrays. Do you have idea of any?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.