0

我试图在字符串中搜索以查找包含任何一组单词的字符串,而不是另一组单词。

到目前为止,我正在使用嵌套stripos语句,如下所示:

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

这不仅不起作用,而且看起来也不必要地冗长。

有什么方法可以构造一个简单的字符串来表示“如果这个字符串包含这些词中的任何一个,但没有这些词,那么就这样做”?

4

2 回答 2

1

你可以很容易地把它浓缩成这样;

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

您还可以执行以下操作会更好(IMO);

if(
    stristr($name, "Name") &&
    (stristr($name, "first") || stristr($name, "for") || stristr($name, "1")) &&
    stristr($name, "error")
)
{
    /* Your code */
}
于 2018-06-26T15:22:03.110 回答
-1

黑白名单。

$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 ) );
于 2018-06-26T15:43:29.723 回答