phpstripos

PHP Multiple 'stripos' statements


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


Solution

  • 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 */
    }