drz49609 2010-10-25 01:35
浏览 49
已采纳

preg_replace中的正则表达式检测url格式并提取元素

I need to replace certain user-entered URLs with embedded flash objects...and I'm having trouble with a regex that I'm using to match the url...I think mainly because the URLs are SEO-friendly and therefore a bit more difficult to parse

URL structure: http://www.site.com/item/item_title_that_can_include_1('_etc-32CHARACTERALPHANUMERICGUID

I need to both detect a match of an URL in that format and capture the 32CHARACTERALPHANUMERICGUID which is always placed after the - in the url

something like this:

$ret = preg_replace('#http://www\.site\.com/item/([^-])-([a-zA-Z0-9]+)#','<embed>itemid=$2</embed>', $ret);

For some reason, the above does not find a match for an URL in the specified format. I'm new to regexes, so I think I'm missing something fairly obvious.

  • 写回答

1条回答 默认 最新

  • drbfxb977777 2010-10-25 01:39
    关注

    You should check out parse_url().

    Examine the results - it was made for parsing URLs. You'll be able to extract the data you require from the tokens returned.

    If you are regex crazy, try this...

    /^http:\/\/www\.site\.com\/item\/[^-]*\-([a-zA-Z0-9]{32})$/
    

    Your example is almost there, but...

    • When you do the not character range, i.e. [^-], you still need a quantifier. I placed *, or 0 or more.
    • You don't seem to use the item title, so we won't bother capturing it.
    • You should use beginning (^) and end ($) anchors if the string is always exactly like that.
    • You say the GUID is 32 chars, so we may as well explicitly state that with the {32} quantifier.
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 机器学习能否像多层线性模型一样处理嵌套数据
  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效