合并 PREG_SPLIT_DELIM_CAPTURE 个结果
Combine PREG_SPLIT_DELIM_CAPTURE results
我正在按照以下格式拆分字符串:
| + anything goes here + single space
以下正则表达式对应于所述模式:
/(\|\S*)/
使用 preg_split
和 PREG_SPLIT_DELIM_CAPTURE
奇怪地 returns 将分隔符分成两部分。是否有标志或选项来组合这些结果输出?
$string = "|one |two |three this is a phrase |four";
$result = preg_split('/(\|\S*)/', $string, NULL, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE);
我得到的:
array(7) {
[0]=>
string(4) "|one"
[1]=>
string(1) " "
[2]=>
string(4) "|two"
[3]=>
string(1) " "
[4]=>
string(6) "|three"
[5]=>
string(18) " this is a phrase "
[6]=>
string(5) "|four"
}
我想要的:
array(5) {
[0]=>
string(5) "|one "
[1]=>
string(5) "|two "
[2]=>
string(7) "|three "
[3]=>
string(17) "this is a phrase "
[4]=>
string(5) "|four"
}
只需在单词末尾捕获另一个空格,您就会得到:
/(\|\S*\h*)/ || /(\|\S*\s*)/
因此您的代码将是:
<?php
$string = "|one |two |three this is a phrase |four";
$result = preg_split('/(\|\S*\s*)/', $string, NULL, PREG_SPLIT_NO_EMPTY |
PREG_SPLIT_DELIM_CAPTURE);
var_dump ($result);
正则表达式 101:https://regex101.com/r/m5M7Dv/1
结果
array(5) { [0]=> string(5) "|one " [1]=> string(5) "|two " [2]=> string(7) "|three " [3]=> string(17) "this is a phrase " [4]=> string(5) "|four" }
我正在按照以下格式拆分字符串:
| + anything goes here + single space
以下正则表达式对应于所述模式:
/(\|\S*)/
使用 preg_split
和 PREG_SPLIT_DELIM_CAPTURE
奇怪地 returns 将分隔符分成两部分。是否有标志或选项来组合这些结果输出?
$string = "|one |two |three this is a phrase |four";
$result = preg_split('/(\|\S*)/', $string, NULL, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE);
我得到的:
array(7) {
[0]=>
string(4) "|one"
[1]=>
string(1) " "
[2]=>
string(4) "|two"
[3]=>
string(1) " "
[4]=>
string(6) "|three"
[5]=>
string(18) " this is a phrase "
[6]=>
string(5) "|four"
}
我想要的:
array(5) {
[0]=>
string(5) "|one "
[1]=>
string(5) "|two "
[2]=>
string(7) "|three "
[3]=>
string(17) "this is a phrase "
[4]=>
string(5) "|four"
}
只需在单词末尾捕获另一个空格,您就会得到:
/(\|\S*\h*)/ || /(\|\S*\s*)/
因此您的代码将是:
<?php
$string = "|one |two |three this is a phrase |four";
$result = preg_split('/(\|\S*\s*)/', $string, NULL, PREG_SPLIT_NO_EMPTY |
PREG_SPLIT_DELIM_CAPTURE);
var_dump ($result);
正则表达式 101:https://regex101.com/r/m5M7Dv/1
结果
array(5) { [0]=> string(5) "|one " [1]=> string(5) "|two " [2]=> string(7) "|three " [3]=> string(17) "this is a phrase " [4]=> string(5) "|four" }