Page 1 of 1

Using preg_quote in preg_replace crashes script.

Posted: Fri Apr 11, 2008 8:39 am
by dmarquard
I'm trying to write a script that temporarily renames all current links in the page (don't ask). I'm using preg_quote within preg_replace for find and replace all instances because, for whatever reason, str_ireplace (which I'd honestly rather use) would replace only half of the instances in the code before giving up. I think my code looks fine, but the page won't even load, so I guess I screwed up somewhere. Let me know if you think you spot a flaw.

Code: Select all

                   $url_source = preg_replace('/' . preg_quote('href="#') . '/', 'preg_replace_url_anchor', $url_source); // Encode anchors.
                    $url_source = preg_replace('/' . preg_quote('href=""') . '/', 'preg_replace_url_null', $url_source); // Encode null links.
                    $url_source = preg_replace('/' . preg_quote('href="http://') . '/', 'preg_replace_url_http', $url_source); // Encode existing HTTP links.
                    $url_source = preg_replace('/' . preg_quote('href="https://') . '/', 'preg_replace_url_https', $url_source); // Encode existing HTTPS links.
                    $url_source = preg_replace('/' . preg_quote('href="ftp://') . '/', 'preg_replace_url_ftp', $url_source); // Encode existing FTP links.
Thanks!

Edit: Alternatively, you can also tell me why you think str_ireplace only replaced half of all instances in the code. :)

Re: Using preg_quote in preg_replace crashes script.

Posted: Fri Apr 11, 2008 8:47 am
by aCa
Why do you use preg_quote inside the pattern? Can't you just escape the illigal chars in your pattern? That should solve your problem.

... I'm kinda tempted to ask WHY you wan't to do this 8)

Re: Using preg_quote in preg_replace crashes script.

Posted: Fri Apr 11, 2008 8:50 am
by dmarquard
aCa wrote:Why do you use preg_quote inside the pattern? Can't you just escape the illigal chars in your pattern? That should solve your problem.

... I'm kinda tempted to ask WHY you wan't to do this 8)
I suppose I could. Hah, I guess that would help. :)

Do you have a list of all characters that should be escaped within preg_replace? And are they escaped with a '\' in all instances?

Thanks. :)