preg_split表达式用于通过分隔符拆分字符串

时间:2020-12-04 22:09:05

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

1 个解决方案

#1


1  

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):

这会产生$ lineArray(注意它是如何保留引号):

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

#1


1  

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):

这会产生$ lineArray(注意它是如何保留引号):

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