duanjiwang2927 2016-12-23 11:53
浏览 23
已采纳

如何使preg_replace处理文件名忽略,文件扩展名?

I have a file name as Dona&ld #Duck .jpg. I want to replace all the special characters before .jpg or any file extension with _ (underscore). Output should be Don_a_ld__Duck__.jpg

How to achieve this using preg_replace? I have done as following.

$fileName ='Don.a&ld #Duck .jpg';
$fileName = trim($fileName);
$fileExtension = substr($fileName,-4);
$fileName = substr($fileName,0,-4); // file name without extension
echo $filename = preg_replace('/[^a-z0-9]/i', '_', $fileName).$fileExtension; 

I do not want append file extension separately.

  • 写回答

2条回答 默认 最新

  • donglian2106 2016-12-23 11:58
    关注

    Use the following solution with a negative lookahead that protects the last dot:

    $fileName ='Don.a&ld #Duck .jpg';
    echo $filename = preg_replace('/[^a-z0-9](?![^.]*$)/i', '_', $fileName);
                                              ^^^^^^^^^ 
    

    See the PHP demo

    The (?![^.]*$) just fails the match if a special char is followed by 0+ chars other than a dot up to the end of the string.

    Note that /[^a-z0-9]/i matches _ and replaces with _, which is a redundant operation. You may avoid it with a \W subpattern:

    preg_replace('/\W(?![^.]*$)/', '_', $fileName)
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 2024-五一综合模拟赛
  • ¥15 下图接收小电路,谁知道原理
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭