Page 1 of 1

Multiline Search

Posted: Fri Oct 12, 2007 5:34 am
by shiznatix
I am trying to do a search that does not worry about the results being on different lines. Well, here is an example:

[usersonly]
multiline stuff
[/usersonly]

I am trying to get a preg_replace on that using this regex:

Code: Select all

preg_replace('#\[usersonly\](.*)\[/usersonly\]#im', 'replacement text', $text);
but this does not work. This regex works fine if the replacement stuff is like this:

[usersonly]multiline stuff[/usersonly]

But that is not enough. How do I go about this?

Posted: Fri Oct 12, 2007 6:50 am
by stereofrog
replace "im" with "is"

Posted: Fri Oct 12, 2007 7:05 am
by shiznatix
super that worked the charm. The only problem now is that it only replaces the text once kinda. Like I have this as my preg_replace code:

Code: Select all

$post['pagetext'] = preg_replace('#\[usersonly\](.*)\[/usersonly\]#is', '*You must be logged in to view this. Please [url="register.php"]open account[/url].*', $post['pagetext']);
and $post['pagetext'] is this:
asdfasdfasdfsafsadfasdf [usersonly]password[/usersonly]

[usersonly]
multiline stuff
[/usersonly]
and the only thing that comes out is this:
asdfasdfasdfsafsadfasdf *You must be logged in to view this. Please open account.*
(the open account is linked properly)

But I am missing the second replacement. Why?

Posted: Fri Oct 12, 2007 7:36 am
by VladSun
You are not missing it :) You are replacing the whole text between the first found "[useronly]" and the very last found [/useronly]. You need the "shortest match" regexp - by using ? special symbol.

That is:

Code: Select all

preg_replace("/\[usersonly\](.*?)\[\/usersonly\]/is", '*You must be logged in to view this. Please [url="register.php"]open account[/url].*', $post['pagetext']);
 

Posted: Fri Oct 12, 2007 7:58 am
by shiznatix
haha yes that was it. Thanks

Modifiers

Posted: Sat Oct 20, 2007 3:54 am
by regexpert
Here is the modifier list for more informaiton.


/i : incasesensitive search
/s: continue searching when find a \n or \r