Search code examples
phpregexpcre

Regex does not match text after last match


I'm trying to get all text but not if it's inside inline code (`) or code block(```). My regex is working fine but the last text doesn't match and I don't know why.

My current regex:

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

You can check out the result here: https://regex101.com/r/lYQnUJ/1/

Maybe anybody has an idea how to solve that problem.


Solution

  • You can use

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

    Details:

    • ``` - triple backtick
    • .*? - any zero or more chars as few as possible
    • ``` - triple backtick
    • | - or
    • ` - a backtick
    • [^`]* - zero or more chars other than a backtick
    • ` - a backtick

    See the regex and PHP demo:

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

    Output:

    Array
    (
        [0] => some text here
    
    some more
    
    
        [1] => 
    
    some 
        [2] =>  too
    
    and more code blocks:
    
    
    
        [3] => 
    
    this text isn't matched...
    )