Substr from end of string php?

断了今生、忘了曾经 提交于 2019-12-10 16:39:11

问题


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?


回答1:


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




回答2:


Here you are:

$picturethumbs = array();

foreach ($picture as $val) {
  if (substr($val, -10) == '_thumb.jpg') {
    $picturethumbs[] = $val;
  }
}


来源:https://stackoverflow.com/questions/19654293/substr-from-end-of-string-php

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!