How can you prevent str_replace from removing all instances of a specific domain in the list?
When using `str_replace` to replace a specific domain in a list, the function will replace all instances of that domain by default. To prevent this, you can use a combination of array functions like `array_map` and `str_replace` to target only the specific domain you want to replace. By iterating through the list and replacing only the desired domain, you can ensure that other instances of the domain are not affected.
<?php
// List of domains
$domains = ['example.com', 'test.com', 'example.com', 'domain.com'];
// Domain to replace
$domain_to_replace = 'example.com';
$new_domain = 'newdomain.com';
// Replace only the specified domain
$domains = array_map(function($domain) use ($domain_to_replace, $new_domain) {
return ($domain == $domain_to_replace) ? $new_domain : $domain;
}, $domains);
print_r($domains);
?>
Keywords
Related Questions
- What are best practices for creating a user search feature in PHP that filters results based on different criteria?
- Are there any potential pitfalls in using underscores at the beginning of variables in PHP?
- How does the storage of file information vary between operating systems, and how does this affect PHP scripts that interact with file metadata?