Checking for multiple words in a string

Status
Not open for further replies.

NSA

sudo apt-get thefuckout.tar.gz
Dec 9, 2011
715
86
Hello,

I am trying to check a string for any words at which point if there is a word found, I want PHP to run a MySQL query. Below is a pseudo example of what I want to happen.

$words = ("word","word1","word2");
$string = "hello word";

if($string contains any $words)
{
echo "True";
}else
{
echo "No word";
}

It would be a huge help if someone has a solution.
Cheers.
 

Quackster

a devbest user says what
Aug 22, 2010
1,765
1,245
PHP:
$words = array();
$words[] = "word1";
$words[] = "word2";
 
if (in_array("word1", $words))
{
    echo "amgg";
}
else
{
  echo "no sorry";
}

try that, not sure my php isn't great xD
 

NSA

sudo apt-get thefuckout.tar.gz
Dec 9, 2011
715
86
Unfortunately that just checks one word. For instance I want it where a string can be "Hello how are you?" and PHP will find for instance "are".
 

IntactDev

Member
Nov 22, 2012
399
71
You would have to use a while() function to repeat it every time it isnt found... and if it's found, then you can echo "The string has been found!"..

I would do it now, but I'm redesigning my website ( )
 

NSA

sudo apt-get thefuckout.tar.gz
Dec 9, 2011
715
86
It would've saved you a lot more time if you'd have just told me how to split the string into words :p
 

Markshall

Русский Стандарт
Contributor
Dec 18, 2010
2,638
2,393
Something like this should do the job just find.

PHP:
<?php
$sentence = "Hello how are you?";
$find    = "are";
 
if (preg_match("/{$find}/i", $sentence)) {
echo "\"{$find}\" has been found!";
}else{
echo "\"{$find}\" has not been found.";
}
?>

The 'i' in the first preg_match parameter means that the word is case-insensitive, so if 'ArE' was in $sentence, it would return true. Remove the 'i' to make the search case-sensitive.
 

RastaLulz

fight teh power
Staff member
May 3, 2010
3,934
3,933
Here's a function I coded a few weeks back which will give you the result you want.
PHP:
    function substring_in_array($String, $SubStrings) {
 
        foreach ($SubStrings as $SubString) {
 
            if(strstr(strtolower($String), strtolower($SubString))) {
 
                return true;
 
            }
 
        }
 
        return false;
 
    }

This is how you'd use that function:
PHP:
<?php
 
$string = 'I went to the store.';
 
$words  = Array('shop', 'store', 'market');
 
if(substring_in_array($string, $words)) {
 
  echo 'One of those words were in the string.';
 
}else{
 
  echo 'None of those words were in the string.';
 
}
 

NSA

sudo apt-get thefuckout.tar.gz
Dec 9, 2011
715
86
Thanks for these, I managed to get it working! :D
 

IntactDev

Member
Nov 22, 2012
399
71
I'm interested in your method of getting this done... how would you extend it's functionality to find how many results were found?
 
Status
Not open for further replies.

Users who are viewing this thread

Top