Benjamin
Benjamin

Reputation: 2123

How to get last digits which are number before '.html' string

there is a string, for example : http://address.com/sef-title-of-topic-1111.html

i could not get 1111 in anyway with regexp in php. Is it possible? How?

my code:

$address = 'http://address.com/sef-title-of-topic-1111.html';

preg_match('#-(.*?)\.html#sim',$address,$result);

Upvotes: 0

Views: 298

Answers (4)

Michele
Michele

Reputation: 6131

If the format is always the same you dont need a regex.

$url = "http://address.com/sef-title-of-topic-1111.html";

echo $str = strrev(array_shift(array_reverse(explode(".", array_shift(explode("-",strrev($url)))))));

edit: sorry my php is a bit rusty

Upvotes: 0

Gga
Gga

Reputation: 4421

If you know that the extension is definitely .html (and not .htm for example) then you could use

$lastNos= substr($input, -9, -4);

Clearly a simple solution but you have not specified why regex is required.

Upvotes: 1

sberry
sberry

Reputation: 132018

If the url example is how they will always appear (ie. ending in hyphen, numbers, .html) then this should work:

$str = "http://address.com/sef-title-of-topic-1111.html";

preg_match('#.*-(\d+)\.html#', $str, $matches);
print_r($matches);

If they won't always match the pattern you gave in your question, then clarify by showing alternative values for your $address value.

Upvotes: 3

Chris Cummings
Chris Cummings

Reputation: 1548

If the URL will always be in this format I would use str_replace to strip the .html then explode by "-" and find the last piece.

Of course all of that is assuming the URL is always in this format.

Upvotes: 0

Related Questions