简体   繁体   中英

preg_split expression to split the string by a delimiter

I am trying to split the line have space and text enclosed.. I am not getting proper output

$line = '"name" "Brand" "EAN"   "shipping" "Combinable"';
$lineArray = preg_split('/^\"\s+\"/', $line);
print_r($lineArray);

You don't need to escape the quotes, and your split is incorrect anchored at the beginning of the string. Try this:

$line = '"name" "Brand" "EAN"   "shipping" "Combinable"';
$lineArray = preg_split('/"\s+"/', $line);

Note that this causes the first element to start with a quote, and the last element to end with a quote. To keep the quotes, use assertions:

$lineArray = preg_split('/(?<=")\s+(?=")/', $line);

This produces a $lineArray like (note how it kept the quotes):

Array ( [0] => "name" [1] => "Brand" [2] => "EAN" [3] => "shipping" [4] => "Combinable" )

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.

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