douturan1807 2013-12-10 17:54
浏览 132
已采纳

PHP正则表达式在URL中的斜杠之间获取特定值

I have a string which has, more or less, 2000 characters and contains URLs (a railway of urls). I want to get specific values from this URL with regex but I have no idea how to use them.

A part of the string would be like this:

$string = [...]http://localhost/project/gallery/http://localhost/project/case/category#/img#/case#/http://localhost/project/case/category#/img#/case#/http://localhost/project/sitemap[...]

What I want is to get everything that matches category#/img#/case#/ for every different category, image and/or case of all occurrences (eg: "main-category/45/main/" and "secondary-category/51/id12").

If category# is more than 1 word, it's joined with a "-" (eg: "main-category").

img# is always a 2 to 3 digit number (eg: "45").

case# varies from plain text (joined with "-" if more than 1 word) to a 4 to 5 characters long string with the two first characters being "id" and the other 2 to 3 characters as numbers (eg1: "main-case", eg2: "id45").

One thing to note, if that helps anyone, is that what I want to get is always after case/.

I would like answers/replies that do not contain loops with substr etc.

  • 写回答

1条回答 默认 最新

  • dongxiaoshe0737 2013-12-10 17:57
    关注

    You can use this regex to match your input URI:

    '~/case/([^/]+)/(\d{2,3})/([^/]+)/~i'
    

    With matching group #1 as category, group #2 as img# and group #3 as case3

    Working demo: http://ideone.com/xrsVtf

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

报告相同问题?

悬赏问题

  • ¥15 kafka 分区副本增加会导致消息丢失或者不可用吗?
  • ¥15 微信公众号自制会员卡没有收款渠道啊
  • ¥15 stable diffusion
  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘
  • ¥15 perl MISA分析p3_in脚本出错
  • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件
  • ¥15 ubuntu虚拟机打包apk错误