duanpanzhu2910 2014-02-06 13:56
浏览 26
已采纳

preg replace不会在php中替换

i have this code to replace a pattern in a php date like this

$input = preg_replace('/\/\-\.\_\s/', '-', $date);

If i pass date in the form mm/dd/yyyy, preg_replace just gives me back the passed date

the expected output should be mm-dd-yyyy what could be wrong

  • 写回答

2条回答 默认 最新

  • duaner5714 2014-02-06 13:59
    关注

    The set of characters you intend to replace with - belong inside a [] character class. In there, the . does not require escaping.

    $out = preg_replace('#[/._\s]#', '-', $date);
    

    When you are dealing with / as one of your expected characters, it is recommended to use a different character such as # as the delimiter.

    $date = '01/02/2013';
    echo preg_replace('#[/._\s]#', '-', $date);
    // 01-02-2013
    
    $date = '01.02.2013';
    echo preg_replace('#[/._\s]#', '-', $date);
    // 01-02-2013
    
    // Or mixed...
    $date = '01 02/2013';
    echo preg_replace('#[/._\s]#', '-', $date);
    // 01-02-2013
    

    In your attempt, not using a character class [] caused your expression to expect the characters /-._\s literally in succession.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度