tags:

views:

67

answers:

4

How do I extract foo from the following URL and store it in a varialbe, using regex in php?

http://example.com/pages/foo/inside.php

I googled quite a bit for an answer but most regex examples were too complex for me to understand.

+1  A: 
preg_match('~pages/(.+?)/~', "http://example.com/pages/foo/inside.php", $matches);
echo $matches[1];
stereofrog
That was quick! Thanks.
Yeti
+1  A: 

If the first part is invariant:

$s = 'http://example.com/pages/foo/inside.php';
preg_match('@^http://example.com/pages/([^/]+).*$@', $s, $matches);
$foo = $matches[1];

The main part is ([^/]+) which matches everything which is not a slash (/). That is, we're matching until finding the next slash or end of the string (if the "foo" part can be the last).

jensgram
+1  A: 

Well, there could be multiple solutions, based on what rule you want the foo to be extracted. As you didn't specify it yet, I'll just guess that you want to get the folder name of the current file (if that's wrong, please expand your question).

<?php
$str = 'http://example.com/pages/foo/inside.php';
preg_match( '#/([^/]+)/[^/]+$#', $str, $match );
print_r( $match );
?>
poke
That's correct, just want the folder name. @stereofrog's answer works. But thanks!
Yeti
Well, my answer works for all urls, just in case you need it :) – Btw. you can upvote answers if you approve them (in addition to accepting one final answer).
poke
A: 
$str = 'http://example.com/pages/foo/inside.php';
$s=parse_url($str);
$whatiwant=explode("/",$s['path']);
print $whatiwant[2];
ghostdog74