Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extract basename from filename in array

i have array with following strings. first im using explode "\n" and the output as below.

[1]=> string(121) "/Microsoft/Windows/Ravemp2300Handler/DeviceArrival/a.exe" 
[2]=> string(139) "/Microsoft/Windows/EventHandlers/Ravemp2300Arrival/b.exe" 
[3]=> string(89) "/Microsoft/Windows/DeviceHandlers/Rio600Handler/c.exe" 
[4]=> string(103) "/Microsoft/Windows/Rio600Handler/EventHandlers/d.exe" 

the following array will be extracted a.exe, b.exe and so on as below.

[1]=> string(121) "a.exe" 
[2]=> string(139) "b.exe" 
[3]=> string(89) "c.exe" 
[4]=> string(103) "d.exe" 

anyone have idea how to solve the problem? i really appreciate it. thank you in advance.

i got the solution, thanks to Leven and Emil Vikström for alternate solution.

$array2 = array_map('basename', $array1);
like image 283
Stream Avatar asked May 30 '26 11:05

Stream


2 Answers

You're looking for basename():

$array2 = array_map('basename', $array1);
like image 79
Leven Avatar answered Jun 02 '26 02:06

Leven


function lastPart($str) {
  return end(explode('/', $str));
}

$array2 = array_map('lastPart', $array1);

What this does is it applies the function lastPart to every element of the array. array_map is called a higher-order function because it takes another function as it's argument, which is a very common idiom in what is called functional programming. PHP is not functional but I still like this type of solutions.

array_filter and usort are two other higher-order functions well worth checking out.

For a more common imperative solution you may just run a foreach loop:

$array2 = array();
foreach($array1 as $value) {
  $array2[] = end(explode('/', $value));
}
like image 26
Emil Vikström Avatar answered Jun 02 '26 01:06

Emil Vikström



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!