Find the first slash on the back (file path)

I have this line.

$line = '/opt/fings/interface/20140905111645811106.txt 0'; 

I used this to disable the final 0/r/n .

 $pos = strpos($lines[$x], ' '); $file = '.'.substr($lines[$x], 0, $pos); 

so I stayed with this /opt/fings/interface/20140905111645811106.txt

But I only need the file name. e.g. 20140905111645811106.txt

Ho, do I take a string from the back until the first slash appears?

+5
source share
7 answers

You can use basename() in this case:

 $line = '/opt/fings/interface/20140905111645811106.txt'; echo basename($line); // 20140905111645811106.txt 
+6
source

Try it -

 $str = '/opt/fings/interface/20140905111645811106.txt'; $file = end(explode('/',$str)); echo $file; 

The output will be - 20140905111645811106.txt

+4
source

Third decision

 echo pathinfo ( '/opt/fings/interface/20140905111645811106.txt', PATHINFO_BASENAME ); 

pathinfo

+3
source

Use strrchr() to find the last occurrence of a character in a string. See: http://php.net/manual/en/function.strrchr.php

$position = strrchr($str, '/');

+2
source

You can use this

 $text = '/opt/fings/interface/20140905111645811106.txt' substr( strrchr( $text, '/' ), 1 ); 
+2
source

Another way: use substr and strrpos

 $filename = substr($line, strrpos($line, "/")+1); 
+2
source

Via preg_match ,

 $line = '/opt/fings/interface/20140905111645811106.txt'; preg_match('~[^/]+$~', $line, $match); echo $match[0]; // 20140905111645811106.txt 
+2
source

Source: https://habr.com/ru/post/1203772/


All Articles