Regex help, please!

Any questions involving matching text strings to patterns - the pattern is called a "regular expression."

Moderator: General Moderators

Post Reply
mjseaden
Forum Contributor
Posts: 458
Joined: Wed Mar 17, 2004 5:49 am

Regex help, please!

Post 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
User avatar
neophyte
DevNet Resident
Posts: 1537
Joined: Tue Jan 20, 2004 4:58 pm
Location: Minnesota

Post 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.
mjseaden
Forum Contributor
Posts: 458
Joined: Wed Mar 17, 2004 5:49 am

Post 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
User avatar
raghavan20
DevNet Resident
Posts: 1451
Joined: Sat Jun 11, 2005 6:57 am
Location: London, UK
Contact:

Post 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
}


?>
User avatar
Ambush Commander
DevNet Master
Posts: 3698
Joined: Mon Oct 25, 2004 9:29 pm
Location: New Jersey, US

Post 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.
mjseaden
Forum Contributor
Posts: 458
Joined: Wed Mar 17, 2004 5:49 am

Post by mjseaden »

Great, thanks to both of you for your help.

Mark
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

Moved to ............... Regex.. dun-dun-dunnnnnnnn.
User avatar
Chris Corbyn
Breakbeat Nuttzer
Posts: 13098
Joined: Wed Mar 24, 2004 7:57 am
Location: Melbourne, Australia

Post 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 ....
Post Reply