Escape slashes to URL with backslashes

This is how you can escape slashes in an URL with an backslash, before doing a preg_replace on the path part of the URL. I have used this before a validation of URL:s containing the swedish characters åäö. I replace the trailing path part of the URL to encoding, but to be able to use preg_replace you need to escape slashes first.

<?php
$link          
= parse_url($item['k_link']);
$path_encoded   = urlencode($link['path']);
$link['path']   = str_replace('/',"\\/", $link['path']);
$item['k_link'] = preg_replace("/".$link['path']."/", $path_encoded, $item['k_link']);
?>
Knowledge keywords: