在正则表达式 reg_split 中使用 splitAt 将它们存储在结果数组中
Using the splitAt in a regex reg_split to store them in the resulting array
有没有办法在正则表达式 preg_split 中使用 splitAt,并将它们与结果一起存储在结果数组中?例如:
$text = " did the great white eat the fishes ";
$text = preg_split("~( did | eat )~", $text, -1, PREG_SPLIT_NO_EMPTY);
print_r($text);
结果:
Array ( [0] => the great white [1] => the fishes )
想要的结果:
Array ( [0] => the great white [1] => eat [2] => the fishes )
您可以使用 PREG_SPLIT_DELIM_CAPTURE
标志来捕获结果数组中使用的分隔符:
$text = " did the great white eat the fishes ";
$wrds='did|eat';
$arr = preg_split("~\h+($wrds)\h+~", preg_replace("/^\h*($wrds)\h+/", "" $text),
-1, PREG_SPLIT_DELIM_CAPTURE));
print_r($arr);
否则:
$arr = preg_split("~^\h+(?:$wrds)\h+|\h+($wrds)\h+~", $text, -1,
PREG_SPLIT_DELIM_CAPTURE|PREG_SPLIT_NO_EMPTY);
输出:
Array
(
[0] => the great white
[1] => eat
[2] => the fishes
)
如果您只想捕获 'did' 或 'eat' 分隔符
中间,您可能必须先检查边缘情况:
^(?: did | eat )|(?: did | eat )$|( did | eat )
使用这些选项 PREG_SPLIT_DELIM_CAPTURE|PREG_SPLIT_NO_EMPTY
在 Perl 中没有可比的 PREG_SPLIT_NO_EMPTY
。
$text = " did the great white eat the fishes ";
$array = preg_split("~( did | eat )~", $text, -1, PREG_SPLIT_NO_EMPTY);
preg_match("~$array[0](.+?)$array[1]~", $text, $match);
$text1 = $array[0];
$text2 = $array[1];
$text3 = $match[1];
echo $text1."<br>".$text3."<br>".$text2;
结果:
the great white
eat
the fishes
有没有办法在正则表达式 preg_split 中使用 splitAt,并将它们与结果一起存储在结果数组中?例如:
$text = " did the great white eat the fishes ";
$text = preg_split("~( did | eat )~", $text, -1, PREG_SPLIT_NO_EMPTY);
print_r($text);
结果:
Array ( [0] => the great white [1] => the fishes )
想要的结果:
Array ( [0] => the great white [1] => eat [2] => the fishes )
您可以使用 PREG_SPLIT_DELIM_CAPTURE
标志来捕获结果数组中使用的分隔符:
$text = " did the great white eat the fishes ";
$wrds='did|eat';
$arr = preg_split("~\h+($wrds)\h+~", preg_replace("/^\h*($wrds)\h+/", "" $text),
-1, PREG_SPLIT_DELIM_CAPTURE));
print_r($arr);
否则:
$arr = preg_split("~^\h+(?:$wrds)\h+|\h+($wrds)\h+~", $text, -1,
PREG_SPLIT_DELIM_CAPTURE|PREG_SPLIT_NO_EMPTY);
输出:
Array
(
[0] => the great white
[1] => eat
[2] => the fishes
)
如果您只想捕获 'did' 或 'eat' 分隔符
中间,您可能必须先检查边缘情况:
^(?: did | eat )|(?: did | eat )$|( did | eat )
使用这些选项 PREG_SPLIT_DELIM_CAPTURE|PREG_SPLIT_NO_EMPTY
在 Perl 中没有可比的 PREG_SPLIT_NO_EMPTY
。
$text = " did the great white eat the fishes ";
$array = preg_split("~( did | eat )~", $text, -1, PREG_SPLIT_NO_EMPTY);
preg_match("~$array[0](.+?)$array[1]~", $text, $match);
$text1 = $array[0];
$text2 = $array[1];
$text3 = $match[1];
echo $text1."<br>".$text3."<br>".$text2;
结果:
the great white
eat
the fishes