Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Substr from end of string php?

Tags:

arrays

php

substr

I have this kind of array, i will make it very simple to understand

$picture = ( 'artist2-1_thumb.jpg',
             'artist2-2.jpg' ,
             'artist2-3_thumb.jpg',
             'artist2-4.jpg',
             'artist2-5_thumb.jpg');

Now i want use substr to get new array that only have thumb, to have new array like this

$picturethumbs = ( 'artist2-1_thumb.jpg',
                   'artist2-3_thumb.jpg',
                   'artist2-5_thumb.jpg');

Can some substr but where to start?

like image 375
Miomir Dancevic Avatar asked Jan 13 '23 01:01

Miomir Dancevic


2 Answers

You could use array_filter() to filter the array, returning only items which match the given condition:

$picturethumbs = array_filter($picture, function($v) {
  return strpos($v, '_thumb') !== false; 
});

Would return all array items which contain the string _thumb. This could be useful if you don't know the extension of the file, or if _thumb appears somewhere other than the end of the string (eg. my_thumb.gif would still match)

$picturethumbs = array_filter($picture, function($v) {
  return substr($v, -10) === '_thumb.jpg'; 
});

Would return all array items where the last 10 characters match _thumb.jpg.

Both (given your example array) output:

array
  0 => string 'artist2-1_thumb.jpg' (length=19)
  2 => string 'artist2-3_thumb.jpg' (length=19)
  4 => string 'artist2-5_thumb.jpg' (length=19)

Here's a demo

like image 111
billyonecan Avatar answered Jan 18 '23 13:01

billyonecan


Here you are:

$picturethumbs = array();

foreach ($picture as $val) {
  if (substr($val, -10) == '_thumb.jpg') {
    $picturethumbs[] = $val;
  }
}
like image 33
Legionar Avatar answered Jan 18 '23 12:01

Legionar