繁体   English   中英

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

[英]PHP Search string, split to array?

我需要在字符串中搜索用逗号分隔的用户名。 必须考虑字符串可能为空,大写或小写,或者也可能在逗号前后包含空格。 它可能是:

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

假设我需要查看"Tom"是否在$string 我最好使用explode将字符串拆分为一个数组,修剪然后检查每个条目吗? 或者,还有更好的方法?

有几种方法可以做到这一点。 这是非常好的和准确的:

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

不区分大小写:

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

您可以手动检查。

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;
}

通过将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