在怀孕期间为所有特殊字符添加尾部斜杠
adding trailing slash to all special characters in preg
我想为所有 preg 特殊字符添加尾部斜线..例如 http://www.youtube.com/watch?v=i9c4PJTDljM
应该转换为 http\:\/\/www\.youtube\.com\/watch\?v\=i9c4PJTDljM
我试过下面的代码
echo preg_quote($url);
但它不会在 backslash.and 中添加尾部斜线 backslash.and 结果是这样的
http\://www\.youtube\.com/watch\?v\=i9c4PJTDljM
<?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
我想为所有 preg 特殊字符添加尾部斜线..例如 http://www.youtube.com/watch?v=i9c4PJTDljM
应该转换为 http\:\/\/www\.youtube\.com\/watch\?v\=i9c4PJTDljM
我试过下面的代码
echo preg_quote($url);
但它不会在 backslash.and 中添加尾部斜线 backslash.and 结果是这样的
http\://www\.youtube\.com/watch\?v\=i9c4PJTDljM
<?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