tags:

views:

31

answers:

2

Hello,

I am trying to capture the following content in PHP using regular expressions:

/*

Name: Test

Description: my test

*/

I have tried the code from here: http://stackoverflow.com/questions/287991/match-everything-inbetween-two-tags-with-regular-expressions but it doesnt capture the new lines.

EDIT: I used the following regular which works on a single line but it stops working as soon as it sees a line break

EDIT2: I want to include that I am running this script on a large piece of text which has a lot of line breaks. I am sure we need to use * because I am unsure of the number of line-break occurrences.

/*(.*?)*/

TIA

+1  A: 

Use the flag s (s stands for dotall)

/*(.*?)*/s

This flag lets the dot also match newline-characters(without this flag it would'nt)

Dr.Molle
I have tried: /*(.*?)[\s]*/*\/ but it doesn't seem to work. I have updated the original post with a better example
Aamir
Take a look at http://php.net/manual/en/reference.pcre.pattern.modifiers.php , (sorry, I should better call it modifier instead of flag )
Dr.Molle
+2  A: 

Ah ok. The dot . in regular expressions does not match newlines per default. You need the /s modifier (after the regex end):

 preg_match("#/[*](.*?)[*]/#s", ...

Also see above, you need to escape the * (with a backslash or surrounding []) and if you want to match / you also need another character to enclose it in. I've used # instead of /

When in doubt, always add /ims. It's no performance drain when you don't use ^ $ or . and letters anyway.

mario
Don't you mean `\/[*](.*?)[*]\/`?
Alec
Great thanks. It seems to work. I would like to know, what is #? Also, I can't seem to find any documentation on /ims as you mentioned - is it a PHP thing?
Aamir
"#" is equivalent to "/". You can use ANY character to enclose regular expressions within. #ims or /ims is just a combination of /i for case-insensitive, and /m for multi-line match and /s for capturing newlines with the dot. It's a difficult topic, so I'd suggest http://www.regular-expressions.info/ which has a very good introduction for PHP preg_match too.
mario
@Alec: No, it works without escaping here. That's why I used # enclosures. Only if you want to use regular slash enclosing style /.../i you have to escape the slashes then.
mario
Thanks a lot mario! Learned something new today
Aamir
@mario, good to know, thanks! Definitely reads a lot easier than \/\/\/s :)
Alec