我试图在字符串中搜索字符串,找出包含任何一组单词的字符串,而不包含另一组的字符串。
到目前为止,我使用的是嵌套stripos语句,如下所示:
if(stripos($name, "Name", true))
{
if((stripos($name, "first", true)) || (stripos($name, "for", true)) || (stripos($name, "1", true)))
{
if(stripos($name, "error"))
{这不仅不起作用,而且似乎也无谓地冗长。
我是否可以构造一个简单的字符串来表示“如果这个字符串包含这些单词中的任何一个,但是没有这些单词,那么就这样做”?
发布于 2018-06-26 15:22:03
你可以很容易地把它浓缩成这样;
if(
stripos($name, "Name", true) &&
(stripos($name, "first", true)) || (stripos($name, "for", true)) || (stripos($name, "1", true)) &&
stripos($name, "error")
)
{
/* Your code */
}你也可以做以下工作,这样做会更好(海事组织);
if(
stristr($name, "Name") &&
(stristr($name, "first") || stristr($name, "for") || stristr($name, "1")) &&
stristr($name, "error")
)
{
/* Your code */
}发布于 2018-06-26 15:43:29
黑名单和白名单。
$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 ) );https://stackoverflow.com/questions/51046366
复制相似问题