【问题标题】: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
【问题讨论】:
标签:
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