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?
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
)
Regular expressions are your friend on this one. I'm assuming that by brackers, you mean an array.
$k = count($slike);
for ($i = 0; $i < $k; $i++) {
$extpos = strrpos($slike[$i],".");
$slike[$i] = substr($slike[$i],0,$extpos);
}
This is no longer regex-dependent, and benchmarks faster than pathinfo().
Using preg_split
in foreach
foreach ($slike as &$value) {
$split = preg_split('/\./', $value);
$value = $split[0]
}
Change the regex to /[^.]+/
to include a.b.jpg
as well.
Try this one:
$slike = array('1.jpg','253455.jpg','32.jpg','477.jpg');
$slike = array_map(function($e){
$e = explode('.', $e);
return $e[0];
}, $slike);
echo "<pre>";
print_r($slike);
echo "</pre>";