0

I'am trying to use regular expression to get just file name from URL for example:

$link = "http://localhost/website/index.php";

$pattern = '/.*?\.php';

preg_match($pattern, $link, $matches);

but it returns "//localhost/website/index.php" instead of "index".

2
  • you can get a file name in the file browser like total commander Commented Mar 30, 2014 at 6:43
  • please explain what do you mean ? Commented Mar 30, 2014 at 6:44

2 Answers 2

2

Does your code even run? You haven't used any delimiters...

With preg_match, you could use a negated class instead, because / matches the first / then .*? will match all the characters up to .php... and if you want to get only index, it would be simplest to use a capture group like so:

$link = "http://localhost/website/index.php";
$pattern = '~([^/]+)\.php~';
preg_match($pattern, $link, $matches);
echo $matches[1];   # Get the captured group from the array $matches

enter image description here

Or you can simply use the basename function:

echo basename($link, ".php");
Sign up to request clarification or add additional context in comments.

2 Comments

@AhmedDousa It's a delimiter. I could have used | instead, or - or # or @ etc. If I had used / as delimiter however, I would have had to use the pattern like this: /([^\/]+)\.php/ (i.e. I would need to escape all the / in the pattern). I usually use ~ if my pattern has any /, so that I don't need to escape them, and this symbol is quite rare, so all the better to use.
@Jerry, I added an explanation with the help of an image. Hope you don't mind :)
2

I think you would be much better off using a function dedicated to the purpose, rather than a custom regular expression.

Since the example you provided is actually a URL, you could use the parse_url function:

http://php.net/manual/en/function.parse-url.php

You should also look at the pathinfo (well done PHP on the naming consistency there!):

http://php.net/manual/en/function.pathinfo.php

You could then do something like this:

$url = 'http://localhost/path/file.php';
$url_info = parse_url($url);
$full_path = $url_info['path'];
$path_info = pathinfo($full_path);
$file_name = $path_info['filename'] . '.' . $path_info['extension'];

print $file_name; // outputs "file.php"

This might seem more verbose than using regular expressions, but it likely to be much faster and, more importantly, much more robust.

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.