Jasper Ketelaar
Jasper Ketelaar

Reputation: 84

Regex include new lines

Current regular expression:

"/\[(.*?)\](.+?)\[\/(.*?)\]/"

Now when I have the following:

[test]textextext[/test] 

it works just fine but it doesn't find

[test]tesxc
tcxvxcv
[/test]

How do I fix this? Help is greatly appreciated.

Upvotes: 1

Views: 806

Answers (4)

Dr.Kameleon
Dr.Kameleon

Reputation: 22810

Just use the /s modifier.

Reference :

s (PCRE_DOTALL) If this modifier is set, a dot metacharacter in the pattern matches all characters, including newlines. Without it, newlines are excluded. This modifier is equivalent to Perl's /s modifier. A negative class such as [^a] always matches a newline character, independent of the setting of this modifier.

http://php.net/manual/en/reference.pcre.pattern.modifiers.php

Upvotes: 0

PedroD
PedroD

Reputation: 6023

Try with this

/\[(.*?)\][^.]+\[\/(.*?)\]/

You can test these regex at regexpal.com

Upvotes: 0

Niet the Dark Absol
Niet the Dark Absol

Reputation: 324610

Actually... the s flag alone may not be such a good idea, because that would allow:

[te
xt]123
456[/tex
t]

I think you might want this:

"(\[(?>([^\]])*)\](.+?)\[/\1\])s"

This uses a few clever tricks:

  • Once-only subpattern for the opening tag, prevents possible backtracking explosion
  • [^\]]* instead of .*?, so the once-only thing works better and this is more explicit as to what ends your repeating
  • End tag uses \1 to match the same as the opening tag, assuming you want [abc]...[/abc] and not [abc]...[/def]
  • Use () instead of // to delimit the regex - parentheses come in pairs so there's no need to escape anything inside (you'll notice I just have / in the closing tag of the pattern instead of \/), but also this can serve as a handy reminder that the first index in the match array is the entire match.

Upvotes: 0

Qtax
Qtax

Reputation: 33908

You can use the /s flag to make . match new lines. For example:

/\[(\w+)](.+?)\[\/\1]/s

Upvotes: 3

Related Questions