2015-07-04 36 views
-1

我要添加斜線所有預浸特殊characters..For例如http://www.youtube.com/watch?v=i9c4PJTDljM應轉換爲http\:\/\/www\.youtube\.com\/watch\?v\=i9c4PJTDljM添加斜線到所有特殊字符在預浸

我嘗試下面的代碼

echo preg_quote($url); 

但它不添加斜線到backslash.and結果是這樣的

http\://www\.youtube\.com/watch\?v\=i9c4PJTDljM 
+5

['preg_quote'](http://php.net/preg_quote),第二個參數用於指定分隔符。 – mario

回答

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); 

?> 

輸出:

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