0

i have the fowling code in my project:

 $title = "In this title we have the word GUN"
 $needed_words = array('War', 'Gun', 'Shooting');
 foreach($needed_words as $needed_word) {
     if (preg_match("/\b$needed_word\b/", $title)) {
     $the_word = "ECHO THE WORD THATS FIND INSIDE TITLE";
     }
 }

I want to check if $title contains one of 15 predefined words, for example lets say: if $title contains words "War, Gun, Shooting" then i want to assign the word that is find to $the_word

Thanks in advance for your time!

mr.d
  • 386
  • 4
  • 18
  • the only think that comes in my mind is to check for every word with if/elseif - but i dont thnik this is the right solution... – mr.d Dec 07 '13 at 11:10
  • Take look at this question http://stackoverflow.com/questions/4366730/how-to-check-if-a-string-contains-specific-words – Andrew Surzhynskyi Dec 07 '13 at 11:11
  • 1
    NO.. NO.. this is right one..http://stackoverflow.com/a/10358573/2611927 – Hardy Dec 07 '13 at 11:13

2 Answers2

0

The best approach would be to use regular expressions, as it is most flexible, and allows you to have more controll over the words which you like to match. To be sure that the string contains words like gun (but also guns), shoot (but also shooting) you can do the following:

$words = array(
    'war',
    'gun',
    'shoot'
);

$pattern = '/(' . implode(')|(', $words) . ')/i';

$if_included = (bool) preg_match($pattern, "Some text - here");
var_dump($if_included);

This matches more then it should. For example it will return true also if the string contains a warning (becouse it starts with war) you can improve this by introducing additinal constraints to certain patterns. For example:

$words = array(
    'war(?![a-z])', // now it will match "war", but not "warning"
    'gun',
    'shoot'
);
Maciej Sz
  • 11,151
  • 7
  • 40
  • 56
0

try this

$makearray=array('war','gun','shooting');
$title='gun';
if(in_array($title,$makearray))
{
$if_included='the value you want to give';
echo $if_included;
}

Note:- This will work if your $title contains exactly the same string that is present as one of the value in the array.Otherwise not.

Let me see
  • 5,063
  • 9
  • 34
  • 47