doumubi6784 2015-09-28 12:46
浏览 15
已采纳

PHP中的正则表达式:强制第二次出现的单词

I need to match a few urls for an application I'm working on;

So, I've got this reference string:

content/course/32/lesson/61/content/348

and I need a pattern that matches either

content

OR

content/course/[number]/lesson/[number]/content/[number]

What I've done so far is come up with this pattern:

$my_regex = "/content(\/?|(\/course\/\d{1,4}\/lesson\/\d{1,4}\/content\/\d{1,4}))$/";

which however has the following problem: This string returns a match which should otherwise not:

content/course/32/lesson/61/content

I'm thinking that it's got something to do with the word content repeating twice but I'm not entirely sure.

Any help is much appreciated.

  • 写回答

2条回答 默认 最新

  • doukunsan5553 2015-09-28 12:51
    关注

    The reason for the match is the alternation.

    content\/?$
    

    matches

    content/course/32/lesson/61/content
    

    To fix this, add a ^ (beginning of line) to the start of your regex to ensure the entire string is matched and not only the ending:

    /^content(\/?|(\/course\/\d{1,4}\/lesson\/\d{1,4}\/content\/\d{1,4}))$/
    

    See it in action

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

报告相同问题?

悬赏问题

  • ¥15 三因素重复测量数据R语句编写,不存在交互作用
  • ¥15 微信会员卡等级和折扣规则
  • ¥15 微信公众平台自制会员卡可以通过收款码收款码收款进行自动积分吗
  • ¥15 随身WiFi网络灯亮但是没有网络,如何解决?
  • ¥15 gdf格式的脑电数据如何处理matlab
  • ¥20 重新写的代码替换了之后运行hbuliderx就这样了
  • ¥100 监控抖音用户作品更新可以微信公众号提醒
  • ¥15 UE5 如何可以不渲染HDRIBackdrop背景
  • ¥70 2048小游戏毕设项目
  • ¥20 mysql架构,按照姓名分表