PHP:使用printf设置字符串格式
我正在尝试编写一个快速字符串格式化例程,以获取未格式化的ISRC代码,并在需要的地方添加连字符 例如,ISRC USMTD9203901应翻译为US-MTD-92-03901。模式是:PHP:使用printf设置字符串格式,php,string,Php,String,我正在尝试编写一个快速字符串格式化例程,以获取未格式化的ISRC代码,并在需要的地方添加连字符 例如,ISRC USMTD9203901应翻译为US-MTD-92-03901。模式是: [A-Z]{2}-[A-Z]{3}-[0-9]{2}-[0-9]{5} 我一直在尝试用substr实现这一点,这产生了以下代码块: function formatISRC($isrc) { $country = substr($isrc, 0, 2); $label = substr($isrc
[A-Z]{2}-[A-Z]{3}-[0-9]{2}-[0-9]{5}
我一直在尝试用substr实现这一点,这产生了以下代码块:
function formatISRC($isrc) {
$country = substr($isrc, 0, 2);
$label = substr($isrc, 2, 3);
$year = substr($isrc, 5, 2);
$recording = substr($isrc, 7);
return $country.'-'.$label.'-'.$year.'-'.$recording;
}
我相信一定有比这更有效的方法来执行字符串操作。您可以使用和:
或更短,带有:
您可以尝试以下方法:
preg_replace(
"/([A-Z]{2})([A-Z]{3})([0-9]{2})([0-9]{5})/", // Pattern
"$1-$2-$3-$4", // Replace
$isrc); // The text
通过“(”和“)”捕获模式中的组,然后在replace中使用该组
function formatISRC($isrc) {
if(!preg_match("/([A-Z]{2})-?([A-Z]{3})-?([0-9]{2})-?([0-9]{5})/", strtoupper($isrc), $matches)) {
throw new Exception('Invalid isrc');
}
// $matches contains the array of subpatterns, and the full match in element 0, so we strip that off.
return implode("-",array_slice($matches,1));
}
preg_replace(
"/([A-Z]{2})([A-Z]{3})([0-9]{2})([0-9]{5})/", // Pattern
"$1-$2-$3-$4", // Replace
$isrc); // The text
function formatISRC($isrc) {
if(!preg_match("/([A-Z]{2})-?([A-Z]{3})-?([0-9]{2})-?([0-9]{5})/", strtoupper($isrc), $matches)) {
throw new Exception('Invalid isrc');
}
// $matches contains the array of subpatterns, and the full match in element 0, so we strip that off.
return implode("-",array_slice($matches,1));
}