Marcus
Marcus

Reputation: 4480

PHP preg_match between text and the first occurrence of -

I'm trying to grab the 12345 out of the following URL using preg_match.

$url = "http://www.somesite.com/directory/12345-this-is-the-rest-of-the-url.html";

$beg = "http://www.somesite.com/directory/";
$close = "\-";
preg_match("($beg(.*)$close)", $url, $matches);

I have tried multiple combinations of . * ? \b

Does anyone know how to extract 12345 out of the URL with preg_match?

Upvotes: 0

Views: 1842

Answers (3)

yankee
yankee

Reputation: 40800

Too slow, I am ^^. Well, if you are not stuck on preg_match, here is a fast and readable alternative:

$num = (int)substr($url, strlen($beg));

(looking at your code I guessed, that the number you are looking for is a numeric id is it is typical for urls looking like that and will not be "12abc" or anything else.)

Upvotes: 0

Emanuil Rusev
Emanuil Rusev

Reputation: 35235

This doesn't use preg_match but would achieve the same thing and would execute faster:

$url = "http://www.somesite.com/directory/12345-this-is-the-rest-of-the-url.html";

$url_segments = explode("/", $url);
$last_segment = array_pop($url_segments);

list($id) = explode("-", $last_segment);

echo $id; // Prints 12345

Upvotes: 1

ircmaxell
ircmaxell

Reputation: 165201

Two things, first off, you need preg_quote and you also need delimiters. Using your construction method:

$url = "http://www.somesite.com/directory/12345-this-is-the-rest-of-the-url.html";

$beg = preg_quote("http://www.somesite.com/directory/", '/');
$close = preg_quote("-", '/');
preg_match("/($beg(.*?)$close)/", $url, $matches);

But, I would write the query slightly differently:

preg_match('/directory\/(\d+)-/i', $url, $match);

It only matches the directory part, is far more readable, and ensures that you only get digits back (no strings)

Upvotes: 3

Related Questions