さて、私は誰かが少しの正規表現で私を助けてくれることを望んでいました.
文字列をクリーンアップしようとしています。
基本的に、私は:
A-Za-z0-9 を除くすべての文字を置換で置き換えます。
置換の連続する複製を置換の単一インスタンスに置換します。
文字列の最初と最後から置換をトリミングします。
入力例:
( && (%()$( )#& #&%&% %(%$ +-_犬が丸太を飛び越えた*(&)$%& )#)@#%&)&^)@# )
必要な出力:
The+dog+jumped+over+the+ログ
私は現在、この非常に混乱したコードを使用していますが、これを達成するためのはるかにエレガントな方法があることを知っています....
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);
}