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
. Am I best to use explode
to split the string into an array, trimming then checking each entry? 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:
function contains($value, $string) {
return preg_match('/(?<=[[:punct:]|[:space:]])(' . $value . ')(?=[[:punct:]|[:space:]])/i', $string, $match);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.