好的,我希望有人能帮我一下正则表达式。
我正在尝试清理一个字符串。
基本上,我正在做以下几件事:
用替换字符替换除A-Za-z0-9之外的所有字符。
将替换字符的连续重复项替换为单个替换字符。
从字符串开头和结尾修剪替换字符。
示例输入:
(&&(%()$()#&#&%&%%(%$+-_The dog jumped over the log*(&)$%&)#)@#%&)&^)@#)
所需输出:
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);
}
能否请一位正则表达式大师给我提供一个更简单/更有效的解决方案?
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);
}