vitorsdcs
vitorsdcs

Reputation: 692

Combine two regular expressions into one, matching first and last part of URL?

How can I combine two regexes?

For example, I have this string:

/path/to/file/name.jpg

I want to match two parts of this string with only one regex, so that I can have "/path/to/file/" (everything but last part of url) and "name.jpg". Is it possible?

Edit: I know there are other ways of doing this using PHP functions, but I need to do it with Regex!

Upvotes: 2

Views: 939

Answers (4)

hek2mgl
hek2mgl

Reputation: 158060

In this special case I would not use a regex at all. Use:

$path = dirname('/path/to/file/name.jpg');       // /path/to/file
$filename = basename('/path/to/file/name.jpg');  // name.jpg

If you need a regex, use something like this:

$str = 'path/to/file/name.jpg';
$pattern = '~(.*)(/.*)~';

preg_match($pattern, $str, $matches);
$path = $matches[1];
$filename = $matches[2];

Upvotes: 1

Teneff
Teneff

Reputation: 32158

Sure it is possible:

/^(?P<path>.*?)(?P<filename>[^\/]*)$/

phpfiddle example

Upvotes: 1

itsmejodie
itsmejodie

Reputation: 4228

if (preg_match('#^(.*?/)([^/]+)$#', $path, $matches))
{
    list($all, $directory, $filename) = $matches;
}

Even though there are specific functions like pathinfo() dirname() and basename()

Upvotes: 4

Burhan Khalid
Burhan Khalid

Reputation: 174632

Use pathinfo():

$foo = '/path/to/file/name.jpg';
$bits = pathinfo($foo);
print_r($bits);

That will give you:

Array
(
    [dirname] => /path/to/file
    [basename] => name.jpg
    [extension] => jpg
    [filename] => name
)

Upvotes: 1

Related Questions