-1

I want to add trailing slash for all the preg special characters..For example http://www.youtube.com/watch?v=i9c4PJTDljM should be converted to http\:\/\/www\.youtube\.com\/watch\?v\=i9c4PJTDljM

I tried below code

echo preg_quote($url);

But it does not add trailing slash to backslash.and result is like this

http\://www\.youtube\.com/watch\?v\=i9c4PJTDljM
Adrian Cid Almaguer
  • 7,815
  • 13
  • 41
  • 63
Vishnu
  • 2,372
  • 6
  • 36
  • 58
  • 5
    [`preg_quote`](http://php.net/preg_quote), second parameter for specifying the delimiter. – mario Jul 04 '15 at 19:39

1 Answers1

1
<?php

$content = 'http://www.youtube.com/watch?v=i9c4PJTDljM';
//With this pattern you found everything except 0-9a-zA-Z
$pattern = "/[_a-z0-9-]/i";
$new_content = '';

for($i = 0; $i < strlen($content); $i++) {
    //if you found the 'special character' then add the \
    if(!preg_match($pattern, $content[$i])) {
        $new_content .= '\\' . $content[$i];
    } else {    
        //if there is no 'special character' then use the character
        $new_content .= $content[$i];
    }   
}   

print_r($new_content);

?>

Output:

http://www.youtube.com/watch\?v\=i9c4PJTDlj

Adrian Cid Almaguer
  • 7,815
  • 13
  • 41
  • 63