tags:

views:

59

answers:

3

So yea, I suck with regular expressions. Needs to be done with php. Thanks. I need to be able to pull out "xx" (will always be 2 lowercase alphabetic chars) and "a12" (can be anything but will always be .php).

String:
http://foo.bar.com/some_directory/xx/a12.php?whatever=youwant
A: 
"([a-z]{2})\/([^/]+)\.php"

make sure you are capturing matches. xx will be in group 1, a12 will be in group 2

Ben Hughes
You mean ([a-z]{2})\/([^/]*)\.php
Jeremy Stein
You're welcome.
Jeremy Stein
I think it's entirely rational to use + instead of * at the end there - it's an extra check on bogus data because it ensures that the filename isn't just be an extension. Either will work, but there's no reason not to have the extra validation.
Chris
Check the edit history. I was commenting on the initial version (which didn't work).
Jeremy Stein
Ah - my bad for nitpicking. ;P
Chris
A: 

/([a-z]{2})/([a-zA-Z0-9_-]+)

$string = http://foo.bar.com/some_directory/xx/a12.php?whatever=youwant


$matches;
preg_match("/([a-z]{2})/([a-zA-Z0-9_\-]+)", $string, $matches);

$part_1 = $matches[1]; //xx
$part_2 = $matches[2]; //a12

Good luck!

Tyler
+1  A: 

Since he's looking for a PHP solution and not just PCRE, I think something like this might be a bit more comprehensive:

$src = 'http://foo.bar.com/some_directory/xx/a12.php?whatever=youwant';
preg_match( '/([a-z]{2})\/([^\/]+)\.php/', $src, $matches );
/* grab "xx" */
$first = $matches[1];
/* grab "a12" */
$second = $matches[2];
Chris
I picked this one because it was the only one that didn't error when ran. I also found it helpful to add some_directory\/ to make sure I had a valid match.
Louis W
Good call. I got tunnel vision on the xx/a12.php piece and didn't even think about the rest of the string - which of course you could either build into the regular expression or do some verification before hand, as in if ( strpos( $src, 'http://foo.bar.com/some_directory/' ) === 0 ) { // regex stuff } else { // error stuff }
Chris