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 maixpy训练模型,模型训练好了以后,开发板通电会报错,不知道是什么问题
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 有没有帮写代码做实验仿真的
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥30 vmware exsi重置后登不上
  • ¥15 c++头文件不能识别CDialog
  • ¥15 Excel发现不可读取的内容