【问题标题】:adding trailing slash to all special characters in preg [duplicate]为 preg 中的所有特殊字符添加斜杠 [重复]
【发布时间】:2015-07-04 19:37:59
【问题描述】:

我想为所有 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

【问题讨论】:

  • preg_quote,用于指定分隔符的第二个参数。

标签: php regex string replace escaping


【解决方案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

【讨论】:

    猜你喜欢
    • 2020-03-15
    • 2020-03-29
    • 2023-03-18
    • 2021-09-02
    • 2021-08-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-23
    相关资源
    最近更新 更多