1

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
  • $id = explode("/", "www.imdb.com/title/tt5807628/")[2]; -> tt5807628 Commented Nov 20, 2017 at 20:46
  • wow :o Thank you! Commented Nov 20, 2017 at 20:51
  • If I or another answer helped you, consider up-voting and marking an answer as correct. Commented Nov 20, 2017 at 20:54

3 Answers 3

1

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];
Sign up to request clarification or add additional context in comments.

1 Comment

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. $id = explode("/", parse_url("www.imdb.com/title/tt5807628/", PHP_URL_PATH))[2];
0

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

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

Comments

0

You can use preg_match as well:

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

$id = $matches[1];

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.