0
我想將java函數轉換爲等效的PHP函數。將java函數轉換爲PHP的破折號編碼
的Java:
/**
* Dash Encoding:
*
* Zeta-Jones <=> Zeta--Jones
* Blade - The Last Installment <=> Blade---The-Last-Installment
* Wrongo -Weird => Wrongo---Weird (decodes to => Wrongo - Weird)
* Wrongo- Weird => Wrongo---Weird (decodes to => Wrongo - Weird)
*/
private static Pattern dashes = Pattern.compile("--+"); // "--" => "-"
private static Pattern blanks = Pattern.compile("\\s\\s+"); // " " => " "
private static Pattern hyphen = Pattern.compile("(?<=[^-\\s])-(?=[^-\\s])"); // like "Zeta-Jones"
private static Pattern dash = Pattern.compile("[\\s]-[\\s]|-[\\s]|[\\s]-"); // like "Blade - The Last Installment"
private static Pattern blank = Pattern.compile("\\s+");
public static String dashEncode(String s) {
if (s == null) return s;
s = blank.matcher(
hyphen.matcher(
dash.matcher(
dashes.matcher(
blanks.matcher(s.trim()).replaceAll(" ") // compress embedded whitespace " " => " "
).replaceAll("-") // trim and compress multiple dashes "---" => "-"
).replaceAll("---") // replace dash with surrounding white space => "---"
).replaceAll("--") // replace single "-" => "--"
).replaceAll("-"); // replace blanks with "-"
return s;
}
到目前爲止,我有:
PHP
function dashEncode($str) {
// replace blanks with "-"
$str = str_replace(' ', '-', $str);
// replace single "-" => "--"
$str = str_replace('-', '--', $str);
return $str;
}
任何幫助表示讚賞。由於
謝謝你的端口 – Yada 2011-12-30 14:57:47
這不是一個真正的端口,你要麼必須創建一個類出來的或展開嵌套函數調用,因爲這並沒有使全局函數裏面太大的意義。我只是用這種方式來演示,並且證明它實際上是在PHP中使用'preg_replace'和'trim'。 – hakre 2011-12-30 15:03:21