PHP Multiple 'stripos' statements

233 Views Asked by At

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"?

2

There are 2 best solutions below

3
Can O' Spam On BEST ANSWER

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 */
}
0
SirPilan On

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 ) );