Derokorian
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:
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)
$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;
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;
ASKER
No luck...
$pattern = '#\[PHP]([\n\r.]*)\[\/PHP\ ]#i';
Does't match one line OR multiple lines now.
$pattern = '#\[PHP]([\n\r.]*)\[\/PHP\
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
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
Awesome! Quick question - What does the s modifier do?
SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
(which allows .* to match more than one line)
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
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).
Require reading here...
http://us.php.net/manual/en/reference.pcre.pattern.modifiers.php
http://us.php.net/manual/en/reference.pcre.pattern.modifiers.php
Try matching [\n\r.]* instead of just .*