2015-01-31 67 views
0

我正在調用api並用自己的url替換遠程url。 http://example.com/a/b/icon_name.gifhttp://example.org/c/d/icon_name.png。域名被替換以及從.gif.png的文件擴展名。替換字符串的兩個部分比使用兩個函數更經濟的方法是什麼?只替換php中的部分字符串

$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

str_replace函數接受陣列,'str_replace函數(陣列('example.com/a/b ('example.org/c/d/','.png'),$ str);' – Federkun 2015-01-31 17:54:20

+0

謝謝,這真的很好,很緊湊! – 2015-01-31 18:11:34

回答

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 
+0

謝謝,非常有幫助! – 2015-01-31 18:10:34