开发者

PHP: String formatting with printf

开发者 https://www.devze.com 2022-12-08 20:33 出处:网络
I am trying to write a quick string formatting routine to take an unformatted ISRC code and add hyphenati开发者_C百科on where it is required.

I am trying to write a quick string formatting routine to take an unformatted ISRC code and add hyphenati开发者_C百科on where it is required.

For example, the ISRC USMTD9203901 should translate to US-MTD-92-03901. The pattern is:

[A-Z]{2}-[A-Z]{3}-[0-9]{2}-[0-9]{5}

I have been trying to implement this with substr and this has produced the following block of code:

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;
}

I am sure there must be a more efficient way of performing string manipulation than this.


You could use sscanf and sprintf:

$parts = sscanf($isrc, '%2s%3s%2d%5d');
return sprintf('%s-%s-%02d-%05d', $parts[0], $parts[1], $parts[2], $parts[3]);

Or shorter with vsprintf:

return vsprintf('%s-%s-%02d-%05d', sscanf($isrc, '%2s%3s%2d%5d'));


You can try this:

preg_replace(
    "/([A-Z]{2})([A-Z]{3})([0-9]{2})([0-9]{5})/",  // Pattern
    "$1-$2-$3-$4",                                 // Replace
    $isrc);                                        // The text

You capture the group in the pattern by '(' and ')' then use the group in the replace.


  1. Filter & check the input
  2. If ok reformat the input and return

Something the likes of:

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));
}
0

精彩评论

暂无评论...
验证码 换一张
取 消