Page 1 of 1

Regex help, please!

Posted: Sun Aug 21, 2005 4:09 pm
by mjseaden
Hello,

I have a string of the form

http://www.mysite.com/some-string-goes-hereX.htm

I'd like to extract the number X - for 'some string goes here', no. of words can be anything.

Would very much appreciate some help.

MS

Posted: Sun Aug 21, 2005 4:18 pm
by neophyte
Well how bout:

Code: Select all

$no = substr($_SERVER['HTTP_REQUEST'], -5);
If you know there will not be a query string and it will always be .htm.

Posted: Sun Aug 21, 2005 4:21 pm
by mjseaden
hi neophyte,

X can be any number of digits


...so it has to be a regex to extract the number itself. Any ideas would be very appreciated.

Mark
-------------------------------
Concerned about peak oil? http://www.peakoil.com

Posted: Sun Aug 21, 2005 5:46 pm
by raghavan20
are you planning for online tutorials???

Code: Select all

<?php

$str1  = "http://www.mysite.com/some-string-goes-here243234.htm";
$str2  = "http://www.mysite.com/some-string-goes-here34.htm";
$str3  = "http://www.mysite.com/some-string-goes-here2434.htm";

$tempArray = split("/", $str2);//split the string with '/' as delimiter
$elementsCount = count($tempArray);
$lastElement = $tempArray[$elementsCount - 1]; //get the last array element
preg_match("/[0-9]+\./", $lastElement, $matches);//look for numbers before a dot
if (count($matches)){
	echo $matches[0]."<br />";//display the first match
}


?>

Posted: Sun Aug 21, 2005 5:53 pm
by Ambush Commander
Or you could change your naming conventions:

http://www.mysite.com/some-string-goes-here.243234.htm

Then it's a simple explode.

Posted: Sun Aug 21, 2005 5:57 pm
by mjseaden
Great, thanks to both of you for your help.

Mark

Posted: Sun Aug 21, 2005 7:19 pm
by feyd
Moved to ............... Regex.. dun-dun-dunnnnnnnn.

Posted: Sun Aug 21, 2005 7:43 pm
by Chris Corbyn

Code: Select all

preg_match('/(\d+)\.[a-z]+$/i', $string, $matches);
echo $matches[1];
Works for any URL of that form regardless of whether the extension is .htm .html .php .php3 etc ....