我正在呼叫api并用我自己的URL替换远程URL。
http://example.com/a/b/icon_name.gif
到http://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
);
答案 0 :(得分:4)
// 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