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条)

报告相同问题?

悬赏问题

  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100
  • ¥15 关于#hadoop#的问题
  • ¥15 (标签-Python|关键词-socket)
  • ¥15 keil里为什么main.c定义的函数在it.c调用不了