0

I'm trying to search within strings to find strings that contain any of a set of words, and none of another set.

So far, I'm using nested stripos statements, like this:

            if(stripos($name, "Name", true))
            {
                if((stripos($name, "first", true)) || (stripos($name, "for", true)) || (stripos($name, "1", true)))
                {
                    if(stripos($name, "error"))
                    {

Not only does this not really work, it also seems needlessly verbose.

Is there any way that I can construct a simple string to say "if this string contains any of these words, but none of these words, then do this"?

user1259798
  • 171
  • 1
  • 16
  • strpos and stripos can return 0 if it matches the beginning of the string, always use strict checks with position functions (=== false or !== false) – Devon Bessemer Jun 26 '18 at 15:25
  • The third parameter to `stripos()` is the start point, so this will start at 1 (true) not 0. – Nigel Ren Jun 26 '18 at 15:25

2 Answers2

1

You can easily condense this as such;

if(
    stripos($name, "Name", true) &&
    (stripos($name, "first", true)) || (stripos($name, "for", true)) || (stripos($name, "1", true)) &&
    stripos($name, "error")
)
{
    /* Your code */
}

You could also do the following which would work better (IMO);

if(
    stristr($name, "Name") &&
    (stristr($name, "first") || stristr($name, "for") || stristr($name, "1")) &&
    stristr($name, "error")
)
{
    /* Your code */
}
Can O' Spam
  • 2,718
  • 4
  • 19
  • 45
-1

Black and whitelists.

$aWhitelist = [ "Hi", "Yes" ];
$aBlacklist = [ "Bye", "No" ];

function hasWord( $sText, $aWords ) {
    foreach( $aWords as $sWord ) {
        if( stripos( $sText, $sWord ) !== false ) {
            return true;
        }
    }
    return false;
}

// Tests
$sText1 = "Hello my friend!"; // No match // false
$sText2 = "Hi my friend!"; // Whitelist match // true
$sText3 = "Hi my friend, bye!"; // Whitelist match, blacklist match // false
$sText4 = "M friend no!"; // Blacklist match // false

var_dump( hasWord( $sText1, $aWhitelist ) && !hasWord( $sText1, $aBlacklist ) );
var_dump( hasWord( $sText2, $aWhitelist ) && !hasWord( $sText2, $aBlacklist ) );
var_dump( hasWord( $sText3, $aWhitelist ) && !hasWord( $sText3, $aBlacklist ) );
var_dump( hasWord( $sText4, $aWhitelist ) && !hasWord( $sText4, $aBlacklist ) );
SirPilan
  • 4,649
  • 2
  • 13
  • 26