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.
CodePudding user response:
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);
CodePudding user response:
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";