Link to home
Start Free TrialLog in
Avatar of Derokorian
DerokorianFlag for United States of America

asked on

Regex confusion

So I have the following regex pattern

$pattern = '#\[PHP](.*)\[\/PHP\]#i';

Which seems to work as long as there are no line breaks in between the php tags and I'm super confused why a line break would... break it. For example this works:

<?php

$str = <<<'STR'
I wrote this function to check if a table exists in the database or not.

[php]if( !is_object($db) || get_class($db) != 'mysqli' ) { // check if $db is a valid MySQLi resource[/php]

Thanks so much for looking at my code!
STR;

$pattern = '#\[PHP](.*)\[\/PHP\]#i';

if( preg_match_all($pattern,$str,$matches) ) {
	var_dump($matches);
	$output = 'SUCCESS';
} else {
	$output = 'FAILED';
}
echo $output;

Open in new window


But this does not. Notice the only difference is the line break (I've also tried two letters and two letters with a LB between them and got the same problem)

<?php

$str = <<<'STR'
I wrote this function to check if a table exists in the database or not.

[php]// check if $db is a valid MySQLi resource
if( !is_object($db) || get_class($db) != 'mysqli' ) { [/php]

Thanks so much for looking at my code!
STR;

$pattern = '#\[PHP](.*)\[\/PHP\]#i';

if( preg_match_all($pattern,$str,$matches) ) {
	var_dump($matches);
	$output = 'SUCCESS';
} else {
	$output = 'FAILED';
}
echo $output;

Open in new window

Avatar of Proculopsis
Proculopsis


Try matching [\n\r.]* instead of just .*
Avatar of Derokorian

ASKER

No luck...

$pattern = '#\[PHP]([\n\r.]*)\[\/PHP\]#i';

Does't match one line OR multiple lines now.
The square brackets are metacharacters and may need to be escaped.  I'll try to show you something in a  moment...
SOLUTION
Avatar of Ray Paseur
Ray Paseur
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Awesome! Quick question - What does the s modifier do?
SOLUTION
Avatar of Terry Woods
Terry Woods
Flag of New Zealand image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
(which allows .* to match more than one line)
ASKER CERTIFIED SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Thanks guy very much! I was using simple str_replace for my other tags, however I needed to be able to run the match(es) from this through highlight_string and was having a problem. I appreciate the great explanations! Always thought . matched any character (without the s modifier).