[英]Regular expression or sprintf-like function to format strings in PHP
我有一组要以特定格式显示的字符串:
| Type | Example | Regex | Output |
|----------|------------|-------------------------|----------------|
| Ref | 0909090 | [0-9]{8} | "09090909" |
| Identity | 6001002003 | [0-9]{10} | "600 100 2003" |
| Internal | M12/45678 | [Mm][0-9]{2}/[0-9]{4,8} | "M12 / 45678" |
PHP中是否有一个允许我传递正则表达式或 sprintf
字符串之类的函数的函数,该函数可以使我以特定方式格式化字符串。
它不需要是任何一个,但是确实需要能够被指定为字符串。 这样一来,我可以将其存储在某种数据对象中,该对象将如下所示:
[
{
name: "identity",
regex: "[0-9]{10}",
format: "%3c %3c %4c" /* or whatever it ends up being */
},
// ....
]
该功能应遵循以下原则 :
echo formatMyString('6001002003', '%3c %3c %4c') // returns "600 100 2003"
在应用preg_replace
和preg_match
检查之前。 例:
function formatMyString($string) {
$patterns = [
[
'name' => 'identity',
'regex' => '^([0-9]{3})([0-9]{3})([0-9]{4})$',
'format' => '$1 $2 $3'
]
];
foreach ($patterns as $pattern) {
if (preg_match('/'.$pattern['regex'].'/', $string)) {
return preg_replace('/'.$pattern['regex'].'/', $pattern['format'], $string);
}
}
return false;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.