Find text after last slash - PHP/REGEX

What is the best way to find the text after the last slash?

/ or \
<?php
 
$file = '/dsafdsf/adsfadsf/asdfdasf/adsf/test.txt';
echo trim(str_replace('_', ' ' , substr($file, strrpos($file,'/') + 1)));
 
echo '<hr />';
 
$file = 'c:\\dsafdsf\\adsfadsf\\asdfdasf\\adsf\\test.txt';
echo trim(str_replace('_', ' ' , substr($file, strrpos($file,'/') + 1)));
 
?>

Open in new window

LVL 16
hankknightAsked:
Who is Participating?
 
thehagmanConnect With a Mentor Commented:
/ is a slash, \ is a backslash - a completely different character.

Maybe try
basename($file)
0
 
ollyatstithiansConnect With a Mentor Commented:
Here is a regex that returns anything between the last / or \ and the end of the string.

Olly.
[^\/]*$

Open in new window

0
 
ollyatstithiansCommented:
... or use basename() like thehagman said.


Olly.
0
 
hankknightAuthor Commented:
basename() --- Why didn't I think of that?  Thanks for keeping it simple.
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.