用str_replace替换两个查找

时间:2016-05-28 21:54:01

标签: php

好的,我有$randomImage,如果我回应一下,我会得到"images/image_name.jpg"。我只希望它回显image_name。我设法隐藏了"images/",但我怎样才能对".jpg"进行同样的操作?

这是我的代码:

$imagesDir = 'images/'; 
$images = glob($imagesDir . '*.{jpg,jpeg,png,gif}', GLOB_BRACE); 
$randomImage = $images[array_rand($images)];
echo str_replace("images/","","$randomImage");

3 个答案:

答案 0 :(得分:2)

尝试在图像路径上使用带有pathinfo参数的PATHINFO_FILENAME

$imagesDir = 'images/'; 
$images = glob($imagesDir . '*.{jpg,jpeg,png,gif}', GLOB_BRACE); 
$randomImage = $images[array_rand($images)];
echo pathinfo($randomImage, PATHINFO_FILENAME);

e.g。

var_dump(pathinfo('images/image_name.jpg', PATHINFO_FILENAME));
//string(4) "image_name"

或者你可以获得文件信息的每一部分。

$pinfo = pathinfo('images/image_name.jpg');
var_dump($pinfo);
/*
array(4) {
  ["dirname"]=>
  string(6) "images"
  ["basename"]=>
  string(14) "image_name.jpg"
  ["extension"]=>
  string(3) "jpg"
  ["filename"]=>
  string(10) "image_name"
}
*/

允许您使用

$pinfo['filename']; //image_name

资源:http://php.net/manual/en/function.pathinfo.php

答案 1 :(得分:0)

试试这个

$replace = array("images/",".jpg");
$images = glob($imagesDir . '*.{jpg,jpeg,png,gif}', GLOB_BRACE); 
$randomImage = $images[array_rand($images)];
echo str_replace($replace,"","$randomImage");

答案 2 :(得分:0)

str_replace()可以将数组作为搜索和替换参数的参数。

示例:

$myString = 'this and that are pretty awesome!';
$search = array('this', 'that');
$replace = array('you', 'I');

$myOutput = str_replace($search, $replace, $myString);

echo $myOutput; // you and I are pretty awesome!

在您的情况下,您可以使用:

$imageName = str_replace(array('/images/','.jpg'), '', '/images/imageName.jpg');