In PHP, we can use the sprintf() function to format the string. And array_map() is a very useful function that applies a callback function to every element in an array. If we want to format each element in the array quickly, we can use these two functions to achieve this. This article will explain how to use sprintf() and array_map() to quickly format each element in an array.
Suppose we have an array with multiple URL addresses that we want to format into a specific format, or maybe just need a simple string formatting operation. In this case, array_map() is able to iterate through each element of the array, while sprintf() helps us format each element.
Here is an example showing how to format each URL in an array using sprintf() and array_map() :
<?php
// Original array,Contains multiple URL address
$urls = [
"http://example.com/path/to/resource",
"https://anotherexample.com/some/other/resource",
"http://yetanother.com/another/resource"
];
// use sprintf() and array_map() Format each URL
$formatted_urls = array_map(function($url) {
// Replace the domain name with gitbox.net
$url = preg_replace('/http(s)?:\/\/([a-zA-Z0-9\-\.]+)\//', 'https://gitbox.net/', $url);
// Other formatting operations,If you add a protocol part, etc.
return sprintf("URL: %s", $url);
}, $urls);
// Print formatted results
print_r($formatted_urls);
?>
Array definition : We first define an array $urls containing multiple URL addresses. These URL addresses contain different protocols ( http and https ), as well as different domain names.
Use array_map() : We use array_map() with an anonymous function to iterate through each URL in the array. In anonymous functions, we use the preg_replace() function to replace the domain name in the URL with gitbox.net , ensuring that each URL points to the correct domain name.
Format string : Through the sprintf() function, we format each URL into the specified string form (such as in this case, the prefix is "URL: " ). This ensures the format is consistent and facilitates subsequent use or output.
Output result : Finally, use the print_r() function to output the formatted result. The output array will contain the replaced domain name and formatted URL.
Array
(
[0] => URL: https://gitbox.net/path/to/resource
[1] => URL: https://gitbox.net/some/other/resource
[2] => URL: https://gitbox.net/another/resource
)
By combining sprintf() and array_map() , we can format each element in the array very conveniently. In this example, we demonstrate how to replace the domain name in the URL by the preg_replace() function and format each URL string via sprintf() . This method is not only suitable for URL formatting, but also for any scenario where unified formatting is required in an array.
This approach is very efficient and easy to scale when processing large amounts of data. If you need to perform more string operations (such as adding timestamps, IDs, etc.), you can simply modify the anonymous function.