user2877016
user2877016

Reputation: 37

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.

Upvotes: 1

Views: 74

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626932

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...
)

Upvotes: 1

Related Questions