vallez vallez - 7 months ago 9
PHP Question

how to get specific text or number id in url with php

i need to get id from url like this
example

http://www.myweb.com/data/11111111111/show/2222222222?auth=c414-4a9a-a0ed-c5034dfdb379


how get
2222222222


output

2222222222


with preg replace i try

$file = $a->url;
$file = preg_replace("/\".*\\\\(.*?)?");
echo $file ;


but not work

Answer

If you know the number will be after /show/ you can use this regex:

.+?\/show\/(\d+).*

as in this:

$file = $a->url;
$file = preg_replace("/.+?\\/show\\/(\\d+).*/", "$1", $file);
echo $file;

Note the / at the beginning and end of the regex. Those are called delimiters, and you need them. Also note that you have to escape the \ characters by typing \\. And preg_replace() takes a minimum of 3 parameters, not 1.

Demo

Explanation:

  • .+? matches any characters in a non-greedy fashion
  • \/show\/ matches /show/
  • (\d+) matches any captures one or more digits
  • .* any characters
  • $1 (in the replacement) replace with the captured group

If you can't rely on /show/ being there and just want the second number that appears, change the regex to this:

https?:\/\/[^\/]+\/\D+\d+\D+\/(\d+).*

So your code becomes:

$file = $a->url;
$file = preg_replace("/https?:\\/\\/[^\\/]+\\/\\D+\\d+\\D+\\/(\\d+).*/", "$1", $file);
echo $file;

Demo

Explanation:

  • http match `http
  • s? optional s
  • :\/\/ match ://
  • [^\/]+ one or more non-/ characters
  • \/ match /
  • \D+ one or more non-digit characters
  • \d+ one or more digits (so, the first number)
  • \D+ one or more non-digit characters
  • \/ match /
  • (\d+) match and capture one or more digits (the second number)
  • .* any characters
  • $1 (in the replacement) replace with the captured group