1

I am trying to write a quick string formatting routine to take an unformatted ISRC code and add hyphenation 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.

3 Answers 3

3

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'));
Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.