PHP - How do I check if a string contains a word?

160 Views Asked by At

Good evening. I'm making an IRC bot that responds when you mention him. What I want to know is how to make him reply when someone actually says his name. This is what I have so far ($match[3] is the message that someone said on a channel and yes, stripos is because I want it case-insensitive ):

if (stripos($match[3], "ircBot") !== false) {
    $isMentioned = true;
}else { $isMentioned = false; }

while this does in fact detect if someone said his name, it only works if he's mentioned at the very beginning of the message so for example:

  • "ircBot is at the beginning of this sentance" would make $isMentioned true
  • "There's ircBot in between this sentance" would make $isMentioned false
  • "At the end of this sentance is ircBot" would make $isMentioned false

I want it to return true if "ircBot" is anywhere inside $match[3] and not just the beginning

3

There are 3 best solutions below

7
On

Use stristr instead

if (stristr($match[3], "ircBot") !== false) {
    $isMentioned = true;
}else { $isMentioned = false; }
1
On

You have to look for word boundaries to avoid someone called MircBot

// using in_array
$isMentioned = in_array('ircbot', preg_split('/\s+/', mb_strtolower($match[3])));

// using regex word boundaries
$isMentioned = preg_match('/\b(ircBot)\b/i', $match[3]);

http://3v4l.org/lh3JT

0
On

I think your error is somewhere else, e.g. the construction of $match[3]. This works fine:

$isMentioned = stripos('This is in the middle of ircBot the string','ircbot') !== false;
echo( $isMentioned ? 'Is Mentioned' : 'Sad ignored bot');