Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to parse this url?

Tags:

php

if I have this url: node/95/pdf/1. How will I able to get the numeric/value 1? Tried the parse_url but gave me the wrong output.

PS: the value 1 is just an example, the id is dynamic depends on what the user click.

like image 276
Wondering Coder Avatar asked Mar 08 '26 08:03

Wondering Coder


2 Answers

I would use sscanf

Untested example:

list($node_id, $pdf_id) = sscanf($url, "node/%d/pdf/%d");

$node_id contains the node id, $pdf_id contains the pdf id. According to your comment: Yes, you can output it with e.g. echo $pdf_id;.

If you need them both in an array, you can remove the list() method, doing it like this:

$ids = sscanf($url, "node/%d/pdf/%d");.

This returns an array with both node and pdf id in $ids.

Finally, if you just need the pdf id, you could do

$id = sscanf($url, "node/95/pdf/%d");.

I just showed how to fetch both because I assumed you may need both numbers from your url.

Edit
seeing all the other answers after posting my solution, I am wondering why everyone is solving this with multiple functions when there is a function available that does exactly what he needs: parsing a string according to a format. This also leads to less sql-injection prone code IMHO. And it doesn't break something when the url gets extended or query strings are appended.

Edit 2 list($node_id, $sub, $sub_id) = sscanf($url, "node/%d/%[^/]/%d"); will get you the "pdf" and it's id separate instead of "node/%d/%s/%d". This is because char / is also matched by %s. Using %[^/] matches everything except the forward slash.

like image 50
pdu Avatar answered Mar 09 '26 20:03

pdu


You can do this:

$id = end(explode('/', 'node/95/pdf/1'));

Example:

$arr = explode('/', 'node/95/pdf/1');
$id = end($arr);
echo $id;  // 1
like image 41
Sarfraz Avatar answered Mar 09 '26 22:03

Sarfraz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!