Using preg_quote in preg_replace crashes script.

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
dmarquard
Forum Newbie
Posts: 2
Joined: Fri Apr 11, 2008 8:32 am

Using preg_quote in preg_replace crashes script.

Post 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. :)
aCa
Forum Newbie
Posts: 11
Joined: Sun Apr 06, 2008 3:43 pm

Re: Using preg_quote in preg_replace crashes script.

Post 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)
dmarquard
Forum Newbie
Posts: 2
Joined: Fri Apr 11, 2008 8:32 am

Re: Using preg_quote in preg_replace crashes script.

Post 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. :)
Post Reply