0

I am calling an api and replacing remote url's with my own ones. http://example.com/a/b/icon_name.gif to http://example.org/c/d/icon_name.png. The domain name is replaced as well as the file name extension from .gif to .png. What is the more economical way to replace two parts of the string than to use two functions?

$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
);
2
  • str_replace accept array, str_replace(array('example.com/a/b/', '.gif'), array('example.org/c/d/', '.png'), $str); Commented Jan 31, 2015 at 17:54
  • Thanks, that's really nice and compact! Commented Jan 31, 2015 at 18:11

1 Answer 1

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);

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


Your case:

$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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.