Reputation: 692
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
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
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
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