0

I have this code, the part I am looking for is the number from the url 1538066650683084805

I use this example

$tweet_url = 'https://twitter.com/example/status/1538066650683084805'

 $arr = explode("/", $tweet_url);
 $tweetID = end($arr);

Which works however sometimes on phones, When people copy and paste the url it has parameters on the end of it like this;

$tweet_url = 'https://twitter.com/example/status/1538066650683084805?q=2&t=1';

When a URL is exploded with the URL above the code doesn't work, how do I get the number 1538066650683084805 in both uses.

Thanks so much.

asked Jun 20, 2022 at 17:52
1

2 Answers 2

4

I would suggest using parse_url to get just the path, then separate that out:

$url = parse_url('https://twitter.com/example/status/1538066650683084805?q=2&t=1');
/*
[
 "scheme" => "https",
 "host" => "twitter.com",
 "path" => "/example/status/1538066650683084805",
 "query" => "q=2&t=1",
 ]
*/
$arr = explode("/", $url['path']);
$tweetID = end($arr);
answered Jun 20, 2022 at 18:04

Comments

1

I would explode first on the question mark and just look at the index 0 .. THEN explode the slash ...

$tweet_url = 'https://twitter.com/example/status/1538066650683084805?q=2&t=1';
$tweet_url = explode('?', $tweet_url)[0];
$arr = explode("/", $tweet_url);
$tweetID = end($arr);

If the question mark does not exist -- It will still return the full URL in $tweet_url = explode('?', $tweet_url)[0]; so it's harmless to have it there.

And this is just me .. But I would write it this way:

$tweet_url = 'https://twitter.com/example/status/1538066650683084805?q=2&t=1';
$tweetID = end(
 explode("/",
 explode('?', $tweet_url)[0]
 ) 
 );
echo $tweetID . "\n\n";
answered Jun 20, 2022 at 17:59

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.