douqingnao9246 2017-05-15 12:50
浏览 23
已采纳

如何创建正确的preg_replace模式?

I have these urls in my magento store: charogh/product/1298/productname the productname will be change for each product,the correct structure is: charogh/product/[0-9]+/[a-zA-z0-9]+

I should change and replace 'product/[0-9]+/' with '' and make the url to 'charogh/' when user enter this url 'charogh/product/[0-9]+/' and do not replace it when user enter this url 'charogh/product/[0-9]+/productname' how can i do it with preg_replace or preg_match?

I use this pattern but it replace in both structures $header=preg_replace('//charogh/product/[0-9]+/',"charogh",$header);

thanks for your help!

  • 写回答

1条回答 默认 最新

  • dongshi9407 2017-05-15 12:56
    关注

    I suggest you anchor the match at the string end with the $ anchor:

    '/\/charogh\/product\/[0-9]+\/?$/'
    

    This way you will prevent matching strings that contain more data after 1+ digits.

    Also, the \/? at the end allows matching 1 or 0 / symbols (i.e. the / is optional).

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

报告相同问题?

悬赏问题

  • ¥15 抖音咸鱼付款链接转码支付宝
  • ¥15 ubuntu22.04上安装ursim-3.15.8.106339遇到的问题
  • ¥15 求螺旋焊缝的图像处理
  • ¥15 blast算法(相关搜索:数据库)
  • ¥15 请问有人会紧聚焦相关的matlab知识嘛?
  • ¥15 网络通信安全解决方案
  • ¥50 yalmip+Gurobi
  • ¥20 win10修改放大文本以及缩放与布局后蓝屏无法正常进入桌面
  • ¥15 itunes恢复数据最后一步发生错误
  • ¥15 关于#windows#的问题:2024年5月15日的win11更新后资源管理器没有地址栏了顶部的地址栏和文件搜索都消失了