更新:第一个问题解决了,是HTML/浏览器的问题
第二个问题:是否有办法将分隔符输出到单独的数组中?如果我使用PREG_SPLIT_DELIM_CAPTURE,它会将分隔符混合到同一个数组中,并使其混淆,而不是PREG_SPLIT_OFFSET_CAPTURE,它为偏移量指定自己的键。
代码:$str = 'world=earth;world!=mars;world>venus';
$arr = preg_split('/([;|])/', $str, -1, PREG_SPLIT_DELIM_CAPTURE);
echo "<pre>";
print_r($arr);
echo "</pre>";
DELIM CAPTURE示例:
Array
(
[0] => world=earth
[1] => ;
[2] => world!=mars
[3] => ;
[4] => world>venus
)
OFFSET CAPTURE示例:
Array
(
[0] => Array
(
[0] => world=earth
[1] => 0
)
[1] => Array
(
[0] => world!=mars
[1] => 12
)
[2] => Array
(
[0] => world>venus
[1] => 34
)
)
从技术上讲,您不能这样做,但在这种特殊情况下,您可以在事后很容易地做到这一点:
print_r(array_chunk($arr, 2));
输出:Array
(
[0] => Array
(
[0] => world=earth
[1] => ;
)
[1] => Array
(
[0] => world!=mars
[1] => ;
)
[2] => Array
(
[0] => world>venus
)
)
参见:array_chunk()
你不能!
一种方法是用preg_match_all
代替preg_split
来获得你想要的:
$pattern = '~[^;|]+(?=([;|])?)~';
preg_match_all($pattern, $str, $arr, PREG_SET_ORDER);
的想法是在前瞻性中放置一个可选的捕获组,用于捕获分隔符。
如果您想要确保不同的结果是连续的,您必须将这个检查添加到模式中:
$pattern = '~G[;|]?K[^;|]+(?=([;|])?)~';
模式细节:
G # the end of the last match position ( A at the begining )
[;|]? # optional delimiter (the first item doesn't have a delimiter)
K # reset all that has been matched before from match result
[^;|]+ # all that is not the delimiter
(?= # lookead: means "followed by"
([;|])? # capturing group 1 (optional): to capture the delimiter
) # close the lookahead
当我运行PHP代码时,这是我从Chrome浏览器得到的结果:
<pre>Array
(
[0] => world=earth
[1] => world!=mars
[2] => world<sun [3]=""> world>venus
)
</sun></pre>
因此preg_split
函数运行良好。这只是HTML中数组转储的问题