简体   繁体   中英

Regex to match everything between hash tags, multiline (PHP)

I'm trying to make a wiki markdown style parser where I have headers defined by hashtags. Eg:

# Heading 1

Some information here below the heading

Another paragraph of information

## Subheading 1

Paragraph related to the subheading

What I'm trying to do is capturing everything between one hash tag and another hashtag (as well as the hash tags themselves)

So in the above, I would want to capture

 Heading 1 (and #)

 Some information here below the heading

 Another paragraph of information

And...

 Subheading 1 (and ##)

 Paragraph related to the subheading

So far I have /(#+) ?(.+)/ and that works perfectly for content on the same line after a hash tag, but not for any text separated by newlines.

However, I can't seem to match and newlines in the (.+) part of the regex pattern, without also gobbling up all of the new lines that start with hash tags.

I'm sure it's something simple.

You can use this negation based regex:

# *([^#]+)

RegEx Demo

Code:

if ( preg_match_all('/# *([^#]+)/', $input, $matches) )
   print_r($matches[1]);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM