我需要做的是在变量中格式化数据,如下所示:
format: xxx-xxx variable: 123456 output: 123-456
问题是我需要能够更改格式,因此静态解决方案不起作用。我还希望能够更改变量大小,例如:
format: xxx-xxx variable: 1234 output: 1-234
注意:所有变量都是数字
编辑我应该清楚它的格式并不总是3组,它可能有更多的“-”作为符号,组将是不稳定的1-22-333-4444它只会在分组中1-5 的
我需要做的是在变量中格式化数据,如下所示:
format: xxx-xxx variable: 123456 output: 123-456
问题是我需要能够更改格式,因此静态解决方案不起作用。我还希望能够更改变量大小,例如:
format: xxx-xxx variable: 1234 output: 1-234
注意:所有变量都是数字
编辑我应该清楚它的格式并不总是3组,它可能有更多的“-”作为符号,组将是不稳定的1-22-333-4444它只会在分组中1-5 的
你最好的选择是preg_replace。
正则表达式需要一些时间来适应,但这可能是你最好的选择......
编辑:
//initial parsing
$val = preg_replace(
'/(\d*?)(\d{1,2}?)(\d{1,3}?)(\d{1,4})$/',
'${1}-${2}-$[3}-${4}',
$inputString
);
//nuke leading dashes
$val - preg_replace('^\-+', '', $val);
关键是让每个集合,除了最右边的一个非贪婪的,允许面向右侧的模式匹配。
您可以实现策略模式,并拥有在运行时可交换的新格式类。如果您以前没有见过它,它看起来很复杂,但它确实有助于可维护性,并允许您随时使用 setFormatter() 切换格式化程序。
class StyleOne_Formatter implements Formatter
{
public function format($text)
{
return substr($text,0,3).'-'.substr($text,3);
}
}
class StyleTwo_Formatter implements Formatter
{
public function format($text)
{
return substr($text,0,1).'-'.substr($text,1);
}
}
然后你会有你的格式化类,就像这样:
class NumberFormatter implements Formatter
{
protected $_formatter = null;
public function setFormatter(Formatter $formatter)
{
$this->_formatter = $formatter;
}
public function format($text)
{
return $this->_formatter->format($text);
}
}
然后你可以像这样使用它:
$text = "12345678910";
$formatter = new NumberFormatter();
$formatter->setFormatter(new StyleOne_Formatter());
print $formatter->format($text);
// Outputs 123-45678910
$formatter->setFormatter(new StyleTwo_Formatter());
print $formatter->format($text);
// Outputs 1-2345678910
如果您要格式化的输入始终是整数,您可以尝试 number_format 并格式化为钱(千等)。这是一个解决方案,它采用任何字符串并将其转换为您想要的格式:
$split_position = 3;
$my_string = '';
echo strrev(implode('-',(str_split(strrev($my_string),$split_position))));
input: 1234; output: 1-234
input: abcdefab; output: ab-cde-fab
input: 1234567 output: 1-234-567