gpt4 book ai didi

java - Dash 编码将 java 函数转换为 PHP

转载 作者:行者123 更新时间:2023-12-01 15:37:20 26 4
gpt4 key购买 nike

我正在尝试将 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;
}

感谢任何帮助。谢谢

最佳答案

我不太了解java,但是在java中Pattern.matcher()replaceAll()一起使用总是函数,这可以在 PHP 中写为 preg_replace()。基本上就是这样。

复制正则表达式模式时,请根据 preg_replace 的需要添加分隔符。接下来,表达式看起来兼容。

/**
* 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)
*/
function dashEncode($s) {
static $pattern = array(
'dashes' => "--+", // "--" => "-"
'blanks' => "\\s\\s+", // " " => " "

'hyphen' => "(?<=[^-\\s])-(?=[^-\\s])", // like "Zeta-Jones"
'dash' => "[\\s]-[\\s]|-[\\s]|[\\s]-", // like "Blade - The Last Installment"
'blank' => "\\s+"
);

$matcher = function($name, $s, $with) use ($pattern) {
isset($pattern[$name]) || die("pattern '$name' undefined.");
return preg_replace("~{$pattern[$name]}~", $with, $s);
};

$s =
$matcher('blank',
$matcher('hyphen',
$matcher('dash',
$matcher('dashes',
$matcher('blanks', trim($s), " ") // compress embedded whitespace " " => " "
, "-") // trim and compress multiple dashes "---" => "-"
, "---") // replace dash with surrounding white space => "---"
, "--") // replace single "-" => "--"
, "-"); // replace blanks with "-"$matcher('blanks', trim($s), " "); // compress embedded whitespace " " => " "
return $s;
}

关于java - Dash 编码将 java 函数转换为 PHP,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8674921/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com