sweet potato
sweet potato

Reputation: 135

Replace only parts of a string in php

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

Upvotes: 0

Views: 269

Answers (1)

Parag Tyagi
Parag Tyagi

Reputation: 8960

// 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

Upvotes: 4

Related Questions