2

I got some link like:

/3/topic/video1148288/

and I want to take the number after video. I can't replace the link with only numbers because there are more before the actual video's id.

I tried

$embed = preg_match("#\b/video([0-9][0-9][0-9][0-9][0-9][0-9][0-9])/#", $raw);

But it doesn't work.

Any help?

웃웃웃웃웃
  • 11,829
  • 15
  • 59
  • 91
ItalianOne
  • 221
  • 1
  • 2
  • 8
  • Define `doesn't work`. It works and here's a [demo](http://regex101.com/r/fT2uE1). However I would replace all those numbers with `[0-9]+` which means match a digit one or more times. If you are certain that there will always be 7 numbers, then you could use `[0-9]{7}`. – HamZa Nov 22 '13 at 17:45

3 Answers3

1

Give this a try:

$raw = "/3/topic/video1148288/";
preg_match("#/video(\d+)/#", $raw, $matches);
$embed = $matches[1];

Working example: http://3v4l.org/oLPMX

One thing to note from looking at your attempt, is that preg_match returns a truthy/falsely value, not the actual matches. Those are found in the third param ($matches in my example).

jszobody
  • 28,495
  • 6
  • 61
  • 72
1
$raw = "/3/topic/video1148288/";

preg_match("/video(\d+)/", $raw, $results);

print "$results[1]";
ederwander
  • 3,410
  • 1
  • 18
  • 23
  • 1
    What if the link was `/3/topic/video1148288/foo`? `.*` is not a very good idea, IMO. – Amal Murali Nov 22 '13 at 17:53
  • Read [the difference between greedy and non-greedy](http://stackoverflow.com/questions/3075130/difference-between-and-for-regex) – HamZa Nov 22 '13 at 17:58
1
preg_match('/(?<=video)\d+/i', $raw, $match);
echo $match[0];
paulie.jvenuez
  • 295
  • 4
  • 11