douyou7102 2017-11-20 20:43
浏览 75
已采纳

php中的子串js

enter code here I'm trying to get out ID from link:

www.imdb.com/title/tt5807628/   - >  tt5807628  

My code in javascript:

  var str = "www.imdb.com/title/tt5807628/";
  var n = str.search("e/tt");
  var res = str.substring(n+2, n+30);
  var ukos = res.search("/");
  var last = res.substring(0, ukos);

I would like to get the same effect in PHP, how to do it?

  • 写回答

3条回答 默认 最新

  • douxi4287 2017-11-20 20:50
    关注

    Based off my comment here, the following code will just give you the ID:

    $id = explode("/", "www.imdb.com/title/tt5807628/")[2];
    

    We use the explode(delimiter, string) function here to break the string at each of the slashes, which creates an index of strings that looks like this:

    array (
        0 => "www.imdb.com"
        1 => "title"
        2 => "tt5707627"
    )
    

    So, as you can see array index 2 is our ID, so we select that after we break the string (which is the [2] at the end of the variable declaration), leaving us with a variable $id that contains just the ID from the link.


    edit:

    You could also use parse_url before the explode, just to ensure that you dont run into http(s):// if the link changes due to user input. - Keja

    $id = explode("/", parse_url("www.imdb.com/title/tt5807628/", PHP_URL_PATH))[2];
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

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