更换字符串的最佳方法?

时间:2010-08-12 17:22:51

标签: php

string '/home/adam/Projects/red/storage/22ff0bc0662bd323891844f6ed342cce2603490ec0_tumb_2.jpg' (length=85)

我需要的只是 http://localhost/storage/22ff0bc0662bd323891844f6ed342cce2603490ec0_tumb_2.jpg

这样做的最佳方式是什么?我的意思是使用strlen? substr_replace? substr?我有点困惑这样做最好的方法是什么?因为有很多方法可以做到这一点。

编辑*没有新手标签:|

    // get from database red/storage/22ff0bc0662bd323891844f6ed342cce2603490ec0_tumb_2.jpg
    $image_path = $this->data['products'][0]['image_small'];
    $exploded = end(explode('/', $image_path));
    $myurl = DOMAIN;
    $myfullurl = $myurl."/storage/".$exploded;

//它有效!但是让我们看看评论可能有更好的方法:)

5 个答案:

答案 0 :(得分:1)

以下是获取图像部分的方法:

$str = '/home/adam/Projects/red/storag/22ff0bc0662bd323891844f6ed342cce2603490ec0_tumb_2.jpg';
$exploded = end(explode('/', $str));
echo $exploded;

<强>结果:

22ff0bc0662bd323891844f6ed342cce2603490ec0_tumb_2.jpg

现在你可以将它连接到例如:

$new_str = 'http://localhost/storage/' . $exploded;
echo $new_str;

<强>结果:

http://localhost/storage/22ff0bc0662bd323891844f6ed342cce2603490ec0_tumb_2.jpg

而且您很可能想要将图像路径连接到您喜欢的文档根目录:

$img_path = $_SERVER['DOCUMENT_ROOT'] . $exploded;

我们的想法是通过将explode指定为分隔符来使用/函数分解字符串。这给了你数组,现在你使用end函数来获取数组的结尾部分,这实际上是你的图像。

答案 1 :(得分:1)

如果路径前缀代表您的文档根路径,那么您可以执行此操作以删除它:

$path = '/home/adam/Projects/red/storage/22ff0bc0662bd323891844f6ed342cce2603490ec0_tumb_2.jpg';
$_SERVER['DOCUMENT_ROOT'] = '/home/adam/Projects/red/';
if (substr($path, 0, strlen($_SERVER['DOCUMENT_ROOT'])) === $_SERVER['DOCUMENT_ROOT']) {
    $uriPath = substr($path, strlen(rtrim($_SERVER['DOCUMENT_ROOT'], '/')));
    echo $uriPath;
}

答案 2 :(得分:0)

我建议您检查字符串是否包含/home/adam/Projects/red,如果是,则使用substr获取后面的部分,然后将其粘贴到http://localost

$path = '/home/adam/Projects/red/storage/*snip*.jpg';
$basePath = "/home/adam/Projects/red";
if (strpos($path, $path) !== false)
    $url = 'http://localhost' . substr($path, strlen($basePath));

答案 3 :(得分:0)

这个是最简单的

str_replace(
  "/home/adam/Projects/red", 
  "http://localhost", 
  "/home/adam/Projects/red/storage/22ff0bc0662bd323891844f6ed342cce2603490ec0_tumb_2.jpg"
);

答案 4 :(得分:0)

$string = '/home/adam/Projects/red/storage/22ff0bc0662bd323891844f6ed342cce2603490ec0_tumb_2.jpg';
str_replace('/home/adam/Projects/red', 'http://localost', $string)