PHP:正则表达式,preg_split

时间:2015-07-06 02:48:01

标签: 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

我该怎么做?

2 个答案:

答案 0 :(得分:1)

如果你只想打破每一行......

preg_match_all()

会给你

$matches

(.*)将使您能够在多行上匹配模式,$matches数组将为您提供所有匹配项。因为它会将整行(包括\ n)视为匹配,这是第一个数组。因此,您希望call匹配的部分位于:auto_no_direct set source="%UserProfile%\AppData\Local\Microsoft\Communicator\" IF EXIST "%UserProfile%\AppData\Local\Microsoft\Communicator\" ( echo Ms Lync Communicator directory found.. echo ^-^> MS Lync 2010 echo Profiles: for %%x in (*.txt) do ( set /a count=count+1 set choice[!count!]=%%x ) for /l %%x in (1,1,!count!) do ( echo %%x] !choice[%%x]! ) set /p select=Type profile then press ENTER: echo Pointer_procent: %select% echo Pointer_wykrzyk: !select! call :subSelect "choice[!select!]" echo Selected: choice[!select!] !Selected! ) ELSE ( echo There not found Communicator directory echo ^-^> No MS Lync installed.. echo ^-^> Terminating..Press any key ) GOTO end :subSelect set "Selected=!%~1!" exit /B 数组的第二个元素中。

答案 1 :(得分:1)

据我了解,如果有^[a-e\d]+\. \v(从下一行开始),您希望在一个或多个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+