我的PHP代码是这样的:
$str = "1. What is love? a. Haddaway b. Haxxaway c. Hassaway d. Hannaway 2. What is love 1.1? a. Haddaway b. Haxxaway c. Hassaway d. Hannaway";
echo "<pre>";
print_r(preg_split('/(?=[\d]+\.)/', $str, -1, PREG_SPLIT_NO_EMPTY));
echo "<pre/>";
输出是:
Array
(
[0] => 1. What is love? a. Haddaway b. Haxxaway c. Hassaway d. Hannaway
[1] => 2. What is love? a. Haddaway b. Haxxaway c. Hassaway d. Hannaway
)
我正试图解决我发现的这个问题。问题是我的$ str是这样的:$str = "1. What is love 1.1? a. Haddaway b. Haxxaway c. Hassaway d. Hannaway
我得到了:
Array
(
[0] => 1. What is love
[1] => 1.1? a. Haddaway b. Haxxaway c. Hassaway d. Hannaway
[2] => 2. What is love? a. Haddaway b. Haxxaway c. Hassaway d. Hannaway
)
我不希望“1.1”在索引[1]上,我希望它保留在索引[0]上。
我已经尝试调整我在preg_split()
中使用的模式但是我没有达到我想要实现的目标......
任何人都可以就我应该做些什么提出建议吗?
答案 0 :(得分:1)
您可以使用否定前瞻来确保DOT后面没有数字:
print_r(preg_split('/(?=\d+\.(?!\d))/', $str, -1, PREG_SPLIT_NO_EMPTY));
Array
(
[0] => 1. What is love? a. Haddaway b. Haxxaway c. Hassaway d. Hannaway
[1] => 2. What is love 1.1? a. Haddaway b. Haxxaway c. Hassaway d. Hannaway
)
答案 1 :(得分:1)
在这里你可以使用边界\B
,它在两个非单词字符和两个单词字符之间匹配。
$str = "1. What is love? a. Haddaway b. Haxxaway c. Hassaway d. Hannaway 2. What is love 1.1? a. Haddaway b. Haxxaway c. Hassaway d. Hannaway";
print_r(preg_split('~(?=\d+\.\B)~', $str,-1, PREG_SPLIT_NO_EMPTY));
输出:
Array
(
[0] => 1. What is love? a. Haddaway b. Haxxaway c. Hassaway d. Hannaway
[1] => 2. What is love 1.1? a. Haddaway b. Haxxaway c. Hassaway d. Hannaway
)