Helpful Information
 
 
Category: Regex Programming
Confused - one regex works, bit a similar one does not work

I'm using preg_replace() in PHP

I have a template file that looks like


Some text here
{%%resources
<li>/*resource*/</li>
%%}
some more text here

I have a pattern that looks like


$pattern = '/\/\*(.+?)\*\//';

using preg_replace() this pattern will match /*resource*/ in the above example

however, I also want to be able to find {%% to %%}, so i tried


$pattern = '/{%%(.+?)%%}/';

but that didn't work, so i tried escaping the % symbols - no luck. Then i tried escaping the { and } instead - no luck. I tried escaping all three characters in the delimiters, but with no luck

What am I doing wrong? :chomp:

Try:



$pattern = '/{%%(.+?)%%}/s';

With the proviso that I don't actually use PHP, I believe the dot character doesn't match newlines by default (it certainly doesn't in Perl, on whose regexp engine PHP's is based). You need the /s modifier to indicate that you want to treat your string as a single line.

That worked a treat, thanks

I was two chapters away from reading the "modifiers" section of http://www.regular-expressions.info/ and had got my version to


'/[{%%][^%%}]+?[%%}]/'

which left me with


{%%}

which I just could not explain










privacy (GDPR)