代码之家  ›  专栏  ›  技术社区  ›  tombazza

PHP:使用printf设置字符串格式

  •  1
  • tombazza  · 技术社区  · 16 年前

    我正在尝试编写一个快速字符串格式化例程,以获取未格式化的ISRC代码,并在需要的地方添加连字符。

    例如,ISRC 应该翻译成 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, 2, 3);
        $year = substr($isrc, 5, 2);
        $recording = substr($isrc, 7);
        return $country.'-'.$label.'-'.$year.'-'.$recording;
    }
    

    3 回复  |  直到 13 年前
        1
  •  3
  •   Gumbo    16 年前

    你可以用 sscanf sprintf :

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

    或者短一点 vsprintf :

    return vsprintf('%s-%s-%02d-%05d', sscanf($isrc, '%2s%3s%2d%5d'));
    
        2
  •  0
  •   NawaMan    16 年前

    您可以尝试以下方法:

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

    通过“(”和“)”捕获模式中的组,然后在replace中使用该组。

        3
  •  0
  •   stroop    16 年前
    1. 过滤及;检查输入
    2. 如果确定,则重新格式化输入并返回

    类似于:

    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));
    }
    
    推荐文章