使用array_filter()函数进行字符串的过滤和搜索

huangapple go评论59阅读模式
英文:

Filtering and searching for strings by array_filter() function

问题

通过array_filter()函数,我可以筛选出年龄超过40岁的人,这返回了正确的答案。但是,如果我想对人们的姓名进行筛选,通过strpos()函数这个方法无法正常工作。例如,如果我想筛选包含词组sapi的姓名,答案应该包括sapirahmatsapi,但实际答案不是这样的。我尝试了其他函数,如strpbrk()函数,但它们也没有给出正确的答案。

如果我一定要使用array_filter()函数和字符串函数,正确的方法是什么?如果字符串函数没有这样的功能,有什么替代方案吗?谢谢。

英文:

I have a list of people's names and ages. Through function array_filter(), I can filter people who are over 40 years old, which returns the correct answer
But if I want to put a filter for the names of people, this issue does not work properly through the Strpos() function, for example, if I want to write the phrase sapi, the answer should include the names sapi and rahmatsapi, but the answer is not like that. I tried other functions such as the strpbrk() function, but they did not give the right answer.

$listL = [
['name' => 'sapi', 'age' => 49],
['name' => 'rahmatsapi', 'age' => 42],
['name' => 'neko', 'age' => 39]];

$filterUser = array_filter($listL, fn($user) => $user['age'] > 40);

$filterUser = array_filter($listL, fn($user) => strpos($user['name'], 'sapi'));

var_dump($filterUser);

If I definitely want to use array_filter()function and string functions, what is the correct way? If string functions do not have such capability, what is the alternative solution?
Thanks

答案1

得分: 0

在我的测试中,它工作正常。我相信这是因为 strpos 需要使用 === 来检查,而不是 ==

$listL = [
    ['name' => 'sapi', 'age' => 49],
    ['name' => 'rahmatsapi', 'age' => 42],
    ['name' => 'neko', 'age' => 39]
];

$filterUserAge = array_filter($listL, function ($user) {
    if ($user['age'] > 40) {
        return $user;
    }
});

$filterUserName = array_filter($listL, function ($user) {
    $pos = strpos($user['name'], 'sapi');
    $achou = false;

    if ($pos === false) {
        return $achou;
    } else {
        $achou = true;
        return $user;
    }
});

print_r($filterUserName);

祝好!

英文:

here in my test it work. I believe that is cause strpos need be check with === rather then ==

$listL = [
['name' => 'sapi', 'age' => 49],
['name' => 'rahmatsapi', 'age' => 42],
['name' => 'neko', 'age' => 39]];

 $filterUserAge = array_filter($listL, function ($user){
    if($user['age'] > 40){
    return $user;
  }
});

$filterUserName = array_filter($listL, function($user){
$pos = strpos($user['name'], 'sapi');
$achou =false;

if($pos === false){
    return $achou;
}else{
   $achou = true;
    return $user;
 }
});

print_r($filterUserName);

Regards

huangapple
  • 本文由 发表于 2023年6月9日 03:37:05
  • 转载请务必保留本文链接:https://go.coder-hub.com/76435188.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定