如何使用php分隔excel中带逗号的全名

问题描述

我有一个项目,它从 excel 中获取名称并将值存储在名字和姓氏中。问题是在excel文件中存储了名称(例如John,Constantine)我如何获取John和Constantine并将其存储在两个不同的变量中?


if(isset($_POST['excel_btn']))
{
    require('import/PHPExcel/PHPExcel.PHP');
    require('import/PHPExcel/PHPExcel/IOFactory.PHP');

    $file=$_FILES['myFile']['tmp_name'];
    

    $obj=PHPExcel_IOFactory::load($file);
    foreach($obj->getWorksheetIterator() as $sheet)
    {
        $getHighestRow=$sheet->getHighestRow();
        for($i=1; $i<=$getHighestRow; $i++){
            $name=$sheet->getCellByColumnAndRow(0,$i)->getValue();
           
             if($name !=''){
                 $query = "INSERT INTO users(name) VALUES('$name')";
            
            $query_run=MysqLi_query($conn,$query);

            }
    }
}

这是我到目前为止所写的内容,但是全名存储在变量 $name

解决方法

您还可以使用正则表达式,该表达式将被逗号或任何空格字符分割。可选标志 PREG_SPLIT_NO_EMPTY 将确保不会返回空匹配项。这个技巧还可以确保修剪。

list($first,$last) = preg_split('/[,\s*]/','John,Doe',-1,PREG_SPLIT_NO_EMPTY);

这也适用于像“ John,Doe”这样的字符串,两者的结果都是

$first = 'John';
$last  = 'Doe';
,

(更新)

使用explode

$pieces = explode(",",$name);
echo trim($pieces[0]); // John
echo trim($pieces[1]); // Constantine

或者,作为@Markus Zeller:

list($first,$last) = explode(',',Constantine')
echo trim($first);
echo trim($last);