PHP:正则表达式、preg_split

标签 php regex

我有一个包含这样内容的字符串。

19. Which of the following conflicting criteria does the problem below satisfe. 2.1
C++ pointers are powerful and very flexible but at the cost of poor intelligibility.
a.  Writability vs Readability
b.  Reliability vs Cost of execution
c.  Writability vs Reliability
d.  Cost of execution vs. Readability
e.  Cost of execution vs. Readability

我想做的就是像这样拆分它。

    [0] => 19.  Which of the following conflicting criteria does the problem below satisfye. 2.1
C++ pointers are powerful and very flexible but at the cost of poor intelligibility.

    [1] => a.   Writability vs Readability

    [2] => b.   Reliability vs Cost of execution

    [3] => c.   Writability vs Reliability

    [4] => d.   Cost of execution vs. Readability

    [5] => e.   Cost of execution vs. Readability

我的正则表达式很弱,我得到了这样的结果。

preg_split('/(?=[a-e\d]+\.(?!\d))/', $entries, -1, PREG_SPLIT_NO_EMPTY);

    [0] => 1
    [1] => 9.   Which of the following conflicting criteria does the problem below satisfy
    [2] => e. 2.1
C++ pointers are powerful and very flexible but at the cost of poor intelligibility.

    [3] => a.   Writability vs Readability

    [4] => b.   Reliability vs Cost of execution

    [5] => c.   Writability vs Reliability

    [6] => d.   Cost of execution vs. Readability

    [7] => e.   Cost of execution vs. Readability

我应该怎么做?

最佳答案

据我了解,您想要拆分为一个或多个 \v垂直空格,如果有 ^[a-e\d]+\. ahead (从下一行开始)。 preg_split功能很好:

$pattern = '/\v+(?=^[a-e\d]+\.)/m';

m 是多行标志,用于使 ^ 插入符匹配行开头(不仅仅是字符串开头)。

print_r(preg_split($pattern, $str));

test at eval.in ;应该给出期望的结果:

Array
(
    [0] => 19. Which of the following conflicting criteria does the problem below satisfe. 2.1
C++ pointers are powerful and very flexible but at the cost of poor intelligibility.
    [1] => a.  Writability vs Readability
    [2] => b.  Reliability vs Cost of execution
    [3] => c.  Writability vs Reliability
    [4] => d.  Cost of execution vs. Readability
    [5] => e.  Cost of execution vs. Readability
)

还有see regex101用于测试分割序列。如果存在中间有空格的空行,请尝试使用 \s+(一个或多个空格)而不是 \v+

关于PHP:正则表达式、preg_split,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31237132/

相关文章:

javascript - 如何转义nodejs中的字符?

php - 使用环境变量覆盖核心 Magento DB 连接

php - 如何传递多对多关系以查看数组[Laravel 5]

java - 空格匹配正则表达式 - Java

php - 密码 PHP 的正则表达式

sql - 查询SQL中的行顺序

php - Withings API 未重定向到我的回调 URL (PHP/OAuth)

php - Laravel - 将动态创建的集合提交给给定模型的数据库

php - 如何组合 2 个不同的过滤器

ios - 在 NSRegularExpression 模式中使用捕获组