<?php
/**
* Replaces values in a URL list with user input, including basic validation.
*
* @param array $urlList An array of URLs with placeholders. Example: ['https://example.com/{id}', 'https://example.com/{name}']
* @param array $userInput An associative array of user input. Example: ['id' => '123', 'name' => 'JohnDoe']
* @return array An array of URLs with replaced values, or an error message if validation fails.
*/
function replaceUrlValues(array $urlList, array $userInput): array
{
$replacedUrls = [];
foreach ($urlList as $url) {
// Basic validation: check if the URL contains placeholders
if (strpos($url, '{') === false || strpos($url, '}') === false) {
$replacedUrls[] = $url; // No placeholders, just add the original URL
continue;
}
$replacedUrl = $url;
$valid = true;
foreach ($userInput as $placeholder => $value) {
// Validate that the placeholder exists in the URL
if (strpos($replacedUrl, '{' . $placeholder . '}') === false) {
return ['error' => "Invalid placeholder: " . $placeholder];
}
// Replace the placeholder with the user input
$replacedUrl = str_replace('{' . $placeholder . '}', $value, $replacedUrl);
}
$replacedUrls[] = $replacedUrl;
}
return $replacedUrls;
}
// Example usage:
$urlList = ['https://example.com/{id}', 'https://example.com/{name}', 'https://example.com/{city}'];
$userInput = ['id' => '456', 'name' => 'JaneSmith'];
$result = replaceUrlValues($urlList, $userInput);
if (isset($result['error'])) {
echo json_encode($result); // Output error message as JSON
} else {
echo json_encode($result); // Output replaced URLs as JSON
}
?>
Add your comment