4

I am trying to make a word filter in php, and I have come across a previous Stackoverlow post that mentions the following to check to see if a string contains certain words. What I want to do is adapt this so that it checks for various different words in one go, without having to repeat the code over and over.

$a = 'How are you ?';

if (strpos($a,'are') !== false) {
echo 'true';
}

Will it work if I mod the code to the following ?......

$a = 'How are you ?';

if (strpos($a,'are' OR $a,'you' OR $a,'How') !== false) {
echo 'true';
}

What is the correct way of adding more than one word to check for ?.

Iain Simpson
  • 8,011
  • 13
  • 47
  • 66

6 Answers6

8

To extend your current code you could use an array of target words to search for, and use a loop:

$a = 'How are you ?';

$targets = array('How', 'are');

foreach($targets as $t)
{
    if (strpos($a,$t) !== false) {
        echo 'one of the targets was found';
        break;
    }
}

Keep in mind that the use of strpos() in this way means that partial word matches can be found. For example if the target was ample in the string here is an example then a match will be found even though by definition the word ample isn't present.

For a whole word match, there is an example in the preg_match() documentation that can be expanded by adding a loop for multiple targets:

foreach($targets as $t)
{
    if (preg_match("/\b" . $t . "\b/i", $a)) {
        echo "A match was found.";
    } else {
        echo "A match was not found.";
    }
}
MrCode
  • 63,975
  • 10
  • 90
  • 112
6

Read it somewhere:

if(preg_match('[word1|word2]', $a)) { } 
Engineer
  • 5,911
  • 4
  • 31
  • 58
1
if (strpos($ro1['title'], $search)!==false or strpos($ro1['description'], $search)!== false or strpos($udetails['user_username'], $search)!== false)
{
//excute ur code
}
pavani
  • 41
  • 4
  • While this code snippet may solve the question, [including an explanation](http://meta.stackexchange.com/questions/114762/explaining-entirely-code-based-answers) really helps to improve the quality of your post. Remember that you are answering the question for readers in the future, and those people might not know the reasons for your code suggestion. – andreas Oct 20 '16 at 18:30
0

If you have a fixed number of words, which is not too big you can easily make it like this:

$a = 'How are you ?';

if (strpos($a,'are') !== false || strpos($a,'you') !== false || strpos($a,'How') !== false) {
echo 'true';
}
Nano
  • 1,398
  • 6
  • 20
  • 32
0

I built methods using both str_contains and preg_match to compare speeds.

public static function containsMulti(?string $haystackStr, array $needlesArr): bool
{
    if ($haystackStr && $needlesArr) {
        foreach ($needlesArr as $needleStr) {
            if (str_contains($haystackStr, $needleStr)) {
                return true;
            }
        }
    }
    return false;
}

preg_match is always a lot slower (2-10 times slower, depending on several factors), but could be useful if you want to extend it for whole-word matching, etc.

public static function containsMulti(?string $haystackStr, array $needlesArr): bool
{
    if ($haystackStr && $needlesArr) {
        $needlesRegexStr = implode('|', array_map('preg_quote', $needlesArr));
        return (bool) preg_match('/(' . $needlesRegexStr . ')/', $haystackStr);
    }
    return false;
}
Redzarf
  • 2,578
  • 4
  • 30
  • 40
0

If you need a multibyte-save version. try this

 /**
 * Determine if a given string contains a given substring. 
 *
 * @param  string  $haystack
 * @param  string|string[]  $needles
 * @param bool $ignoreCase
 * @return bool
 */
public static function contains($haystack, $needles, $ignoreCase = false)
{
    if($ignoreCase){
        $haystack= mb_strtolower($haystack);
        $needles = array_map('mb_strtolower',$needles);
    }
    foreach ((array) $needles as $needle) {
        if ($needle !== '' && mb_strpos($haystack, $needle) !== false) {
            return true;
        }
    }

    return false;
}
  • While this code may answer the question, providing additional context regarding *how* and/or *why* it solves the problem would improve the answer's long-term value. Especially why it's better than the [eight years old accepted one](https://stackoverflow.com/a/19178352/3749896). – Sven Eberth Aug 26 '21 at 22:45