正则表达式在最后一次匹配后不匹配文本

时间:2021-07-03 10:41:54

标签: php regex pcre

我正在尝试获取所有文本,但如果它位于内联代码 (`) 或代码块 (```) 内,则不会。我的正则表达式工作正常,但最后一个文本不匹配,我不知道为什么。

我当前的正则表达式:

(.*?)`{1,3}(?:.*?)`{1,3}(.*?)

您可以在此处查看结果:https://regex101.com/r/lYQnUJ/1/

也许有人知道如何解决这个问题。

1 个答案:

答案 0 :(得分:1)

你可以使用

preg_split('~```.*?```|`[^`]*`~s', $text)

详情

  • ``` - 三重反引号
  • .*? - 尽可能少的零个或多个字符
  • ``` - 三重反引号
  • | - 或
  • ` - 反引号
  • [^`]* - 除反引号外的零个或多个字符
  • ` - 反引号

参见 regexPHP demo

<?php

$text = 'your_text_here';
print_r(preg_split('~```.*?```|`[^`]*`~s', $text));

输出:

Array
(
    [0] => some text here

some more


    [1] => 

some 
    [2] =>  too

and more code blocks:



    [3] => 

this text isn't matched...
)
相关问题