在preg中为所有特殊字符添加尾部斜杠

时间:2015-07-04 19:38:00

标签: php regex string replace escaping

我想为所有preg特殊字符添加尾部斜杠。例如,http://www.youtube.com/watch?v=i9c4PJTDljM应转换为http\:\/\/www\.youtube\.com\/watch\?v\=i9c4PJTDljM

我试过下面的代码

echo preg_quote($url);

但它不会向反斜杠添加尾部斜杠。结果就像这样

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

1 个答案:

答案 0 :(得分: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