Multiline Search

Any questions involving matching text strings to patterns - the pattern is called a "regular expression."

Moderator: General Moderators

Post Reply
User avatar
shiznatix
DevNet Master
Posts: 2745
Joined: Tue Dec 28, 2004 5:57 pm
Location: Tallinn, Estonia
Contact:

Multiline Search

Post 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?
User avatar
stereofrog
Forum Contributor
Posts: 386
Joined: Mon Dec 04, 2006 6:10 am

Post by stereofrog »

replace "im" with "is"
User avatar
shiznatix
DevNet Master
Posts: 2745
Joined: Tue Dec 28, 2004 5:57 pm
Location: Tallinn, Estonia
Contact:

Post 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?
User avatar
VladSun
DevNet Master
Posts: 4313
Joined: Wed Jun 27, 2007 9:44 am
Location: Sofia, Bulgaria

Post 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']);
 
Last edited by VladSun on Thu Feb 07, 2008 3:03 pm, edited 1 time in total.
There are 10 types of people in this world, those who understand binary and those who don't
User avatar
shiznatix
DevNet Master
Posts: 2745
Joined: Tue Dec 28, 2004 5:57 pm
Location: Tallinn, Estonia
Contact:

Post by shiznatix »

haha yes that was it. Thanks
regexpert
Forum Newbie
Posts: 7
Joined: Sat Oct 20, 2007 3:41 am

Modifiers

Post by regexpert »

Here is the modifier list for more informaiton.


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