简体   繁体   English

PHP搜索字符串,拆分为数组?

[英]PHP Search string, split to array?

I need to search a string for usernames separated by a comma. 我需要在字符串中搜索用逗号分隔的用户名。 Have to consider the string might be empty, upper or lowercase, or might contain spaces before or after commas too. 必须考虑字符串可能为空,大写或小写,或者也可能在逗号前后包含空格。 It could be: 它可能是:

$string = "Chris, Tom,Jeff,Roger"
$string = "Chris,Tom , Jeff ,Roger"
$string = ",,,,Chris,tom,Jeff,Roger,,,,"
etc...

Say I need to see if "Tom" is in $string . 假设我需要查看"Tom"是否在$string Am I best to use explode to split the string into an array, trimming then checking each entry? 我最好使用explode将字符串拆分为一个数组,修剪然后检查每个条目吗? Or is there a better way? 或者,还有更好的方法?

There are several ways to do it. 有几种方法可以做到这一点。 This is perfectly fine and accurate: 这是非常好的和准确的:

$found = in_array('Tom', array_filter(explode(',', $string)));

Case insensitive: 不区分大小写:

$found = in_array('tom', array_filter(explode(',', strtolower($string))));

You can check it manually. 您可以手动检查。

public function splitNames() {
    $string = ",,,,Chris,tom,Jeff,Roger,,,,";
    $splited = explode(",", $string);
    foreach ($splited as $name) {
        if ($name == null || $name == "") {
            continue;
        } else {
            $names[] = ucfirst(strtolower(trim($name)));
        }
    }

    return $names;
}

Using preg_match with the i modifier you can verify whether your string contains your data in a case insensitive manner: 通过将preg_matchi修饰符一起使用,可以验证字符串是否以不区分大小写的方式包含数据:

function contains($value, $string) {
    return preg_match('/(?<=[[:punct:]|[:space:]])(' . $value . ')(?=[[:punct:]|[:space:]])/i', $string, $match);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM