Php – preg_replace(), no ending delimiter ‘$’ found

apachePHPpreg-replacewindows

Alright, this problem seems to be way above my head!

I have this code:

$request=preg_replace('$(^'.str_replace('$','\$',$webRoot).')$i','',$requestUri);

This throws me an error:

preg_replace(): No ending delimiter '$' found

But here's the thing, that ending delimeter is certainly there.

After that function call I echoed out the following:

echo $webRoot;
echo $requestUri;
echo '$(^'.str_replace('$','\$',$webRoot).')$i';

This is the result of those echoes:

/
/en/example/
$(^/)$i

What is funny is that if I do this directly:

preg_replace('$(^/)$i','',$requestUri);

..it works. But this also fails:

$tmp=str_replace('$','\$',$webRoot);
preg_replace('$(^'.$tmp.')$i','',$requestUri);

And just to be thorough, I also tested what echo $tmp gives, and it does give the proper value:

/

Is it a bug in PHP in Windows? I tried it out on Linux server and it worked as expected, it didn't throw this error. Or am I missing something?

Just to make sure, I even updated PHP to latest Windows version (5.4.2) and the same thing happens.

Best Answer

Well, I personally would use another character as a delimiter like '#' since the $ char is a regexp special char which matches at the end of the string the regex pattern is applied to. That said the few times I had to work on windows servers I found that every regular expressions has to be passed through preg_quote function, nevermind if it contains or not regexp special chars.

$request=preg_replace('#(^'.preg_quote($webRoot).')#i','',$requestUri);
Related Topic