dongye1912 2016-09-23 18:19
浏览 33
已采纳

提取数字和字符串扩展的正则表达式[关闭]

I use code below for extract numbers and file name of strings with problem standardization

30183308__90_.jpeg
30193253-(100).jpg
30193253__100__.jpg 
30193253_ _100_ _.jpg 

Use this function

public function refactorFileName($filename)
{
    $array = preg_split("/[^A-Za-z0-9]/", $filename);
    foreach($array as $key => $value) {
        if($value == "") {
            unset($array[$key]);
        }
    }
    $array              = array_values($array);
    $standardFilename   = $array[0].'.'.$array[2];
    $indexFile          = $array[1];

    return compact("indexFile","standardFilename");
}

$filename = '30193253_ _100_ _.jpg';
extract(refactorFileName($filename));
echo "New File name -> ".$standardFilename.PHP_EOL;
echo "Index for file -> ".$indexFile.PHP_EOL;

This show (correct):

New File name -> 30193253.jpg
Index for file -> 100

I think there're a better code for regex expresion.

EDIT: It's possible better code on preg_split or better code in general for this question?

  • 写回答

1条回答 默认 最新

  • dousenjue3214 2016-09-23 19:27
    关注

    Two things: 1) It will be easier if you put a quantifier in your pattern (to avoid the useless foreach after). (Note that preg_split has also the option PREG_SPLIT_NO_EMPTY to avoid empty items.)
    2) sometimes too much verbosity kills the verbosity.

    Your can rewrite it this way:

    function refactorFileName($filename) {
        $p = preg_split('~[\W_]+~', $filename, 3);
    
        return [ 'indexFile' => $p[1], 'standardFilename' => "$p[0].$p[2]" ];
    }
    

    Or if you want to be more verbose:

    function refactorFileName($filename) {
        list($name, $index, $ext) = preg_split('~[\W_]+~', $filename, 3);
    
        return [ 'indexFile' => $index, 'standardFilename' => "$name.$ext" ];
    }
    

    (As an aside, when you already have a working code, ask your question on codereview instead of SO)

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器