仅显示不包含的数组值


Only display array values that don't contain

foreach ($prefs as $who => $pref) {
 if($who != 'public'){
  $team_users .=$who.',';
  }
 }       
echo $team_users;

我只想显示不包含文本"public"的数组中的数据,在某些情况下,它可能是 publicXX 或 public1234 等。

您可以将array_filter()与回调一起使用来实现此目的:

$result = array_filter($prefs, function($item) {
    return (strpos($item, 'public') === FALSE);
});
echo implode(',', $result);

http://us3.php.net/strpos

if (strpos($who, 'public') === false) {
  //some code
} else {
  //some code
}

I'd like to only display data from the array that does not contain the text 'public' in some cases it could be publicXX or public1234, etc.

改变:

if($who != 'public'){...}

对此:

if(strpos($who, 'public') !== false){...}
foreach ($prefs as $who => $pref) {
    if(strpos($who, 'public') !== false){
        $team_users .=$who.',';
    }
}       
echo $team_users;

你可以尝试这样的事情:

foreach ($prefs as $who => $pref) {
   if(!preg_match("/public/i", $who)){
       $team_users .= $who.',';
   }
} 
<?php
$a = array('public1', 'asdqwe', 'as33publics', 'helloworld');
$text = implode(', ', array_filter($a, function($v) {
    return strstr($v, 'public') === false;
}));
echo $text;

我会用正则表达式来做。

$pattern = '/public/'; 
if(preg_match($pattern,$who)){
//skip to the next entry
}