【发布时间】:2012-11-18 10:27:16
【问题描述】:
好的,我希望有人可以帮助我使用一点正则表达式。
我正在尝试清理字符串。
基本上,我是:
将除 A-Za-z0-9 之外的所有字符替换为替换字符。
用单个替换实例替换连续重复的替换。
从字符串的开头和结尾修剪替换。
示例输入:
(&&(%()$()#&#&%&%%(%$+-_狗跳过去日志*(&)$%&)#)@#%&)&^)@#)
所需输出:
The+dog+jumped+over+the+log
我目前正在使用这个非常混乱的代码,只是知道有一种更优雅的方式来完成这个......
function clean($string, $replace){
$ok = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
$ok .= $replace;
$pattern = "/[^".preg_quote($ok, "/")."]/";
return trim(preg_replace('/'.preg_quote($replace.$replace).'+/', $replace, preg_replace($pattern, $replace, $string)),$replace);
}
Regex-Fu 大师能否给我一个更简单/更有效的解决方案?
Botond Balázs 和 hakre 提出并解释了一个更好的解决方案:
function clean($string, $replace, $skip=""){
// Escape $skip
$escaped = preg_quote($replace.$skip, "/");
// Regex pattern
// Replace all consecutive occurrences of "Not OK"
// characters with the replacement
$pattern = '/[^A-Za-z0-9'.$escaped.']+/';
// Execute the regex
$result = preg_replace($pattern, $replace, $string);
// Trim and return the result
return trim($result, $replace);
}
【问题讨论】:
-
对于 1 和 2,您可以尝试用替换替换
[^A-Za-z0-9]+。 -
我讨厌 stackoverflow 强迫我选择一个答案......
-
我认为将模式放在单独变量中的版本更具可读性。
-
我为代码示例选择了 Botond Balázs 的答案。但我想拥抱/感谢 hakre 的深入解释和帮助。谢谢大家!
标签: php regex string clean-urls code-cleanup