仅替换 php 中的字符串的一部分

Replace only parts of a string in php

我正在调用一个 api 并将远程 url 替换为我自己的。 http://example.com/a/b/icon_name.gifhttp://example.org/c/d/icon_name.png。域名以及文件扩展名从 .gif 替换为 .png。替换字符串的两个部分比使用两个函数更经济的方法是什么?

$hourlyUrl = array_map(
    function($str) {
        return str_replace('example.com/a/b/', 'example.org/c/d/', $str);
    },
$hourlyUrl
);

$hourlyUrl = array_map(
    function($str) {
        return str_replace('.gif', '.png', $str);
    },
$hourlyUrl
);
// Provides: You should eat pizza, beer, and ice cream every day
$phrase  = "You should eat fruits, vegetables, and fiber every day.";
$healthy = array("fruits", "vegetables", "fiber");
$yummy   = array("pizza", "beer", "ice cream");

$newphrase = str_replace($healthy, $yummy, $phrase);

文档:
http://php.net/manual/en/function.str-replace.php


您的情况:

$old_url = "http://example.com/a/b/icon_name.gif";
$old = array("example.com/a/b/", ".gif");
$new = array("example.org/c/d/", ".png");

$new_url = str_replace($old, $new, $old_url);

// Output: http://example.com/c/d/icon_name.png