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?

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];

With explode function then you can see each part by looping through the array

$varArray = explode( '/', $var );

You can use preg_match as well:

preg_match('~www\.imdb\.com/title/([^/]*)/~', 'www.imdb.com/title/tt5807628/', $matches);

$id = $matches[1];