0

I need a regular expression that would take the string after the last forward slash.

For example, considering I have the following string:

C:/dir/file.txt

I need to take only the file.txt part (string).

Thank you :)

3 Answers 3

5

You don't need a regex.

$string = "C:/dir/file.txt";

$filetemp = explode("/",$string);

$file = end($filetemp);

Edited because I remember the latest PHP spitting errors out about chaining these types of functions.

Sign up to request clarification or add additional context in comments.

Comments

3

If your strings are always paths you should consider the basename() function.

Example:

$string = 'C:/dir/file.txt';

$file = basename($string);

Otherwise, the other answers are great!

Comments

1

The strrpos() function finds the last occurrence of a string. You can use it to figure out where the file name starts.

$path = 'C:/dir/file.txt';
$pos  = strrpos($path, '/');
$file = substr($path, $pos + 1);
echo $file;

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.