0

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
1
  • Just a note - a few of the responses so far seem to have accidentally forgotten to escape a forward slash or two in their regular expression, so whichever answer suits you, be sure to double-check that or PHP will likely throw you garbage about unknown modifiers and such. Cheers! Commented Jul 9, 2009 at 19:57

3 Answers 3

1

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];
Sign up to request clarification or add additional context in comments.

2 Comments

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.
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, 'foo.bar.com/some_directory' ) === 0 ) { // regex stuff } else { // error stuff }
0
"([a-z]{2})\/([^/]+)\.php"

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

1 Comment

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.
0

/([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!

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.