Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I remove the file extension from each string in a PHP array?

Tags:

arrays

php

I have an array of strings, each string containing the name of an image file:

$slike=(1.jpg,253455.jpg,32.jpg,477.jpg);

I want new array, to look like this:

$slike=(1,253455,32,477);

How can I remove the file extension from each string in this array?

like image 302
Tanja Pakovic Avatar asked Nov 17 '25 14:11

Tanja Pakovic


1 Answers

If you're working with filenames, use PHP's built in pathinfo() function. there's no need to use regex for this.

<?php

# your array
$slike = array('1.jpg','253455.jpg','32.jpg','477.jpg');

# if you have PHP >= 5.3, I'd use this
$slike = array_map(function($e){
    return pathinfo($e, PATHINFO_FILENAME);
}, $slike);

# if you have PHP <= 5.2, use this
$slike = array_map('pathinfo', $slike, array_fill(
    0, count($slike), PATHINFO_FILENAME
));

# dump
print_r($slike);    

Output

Array
(
    [0] => 1
    [1] => 253455
    [2] => 32
    [3] => 477
)
like image 166
maček Avatar answered Nov 19 '25 05:11

maček



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!