1. <?php
  2. /**
  3. * Replaces values in a URL list with user input, including basic validation.
  4. *
  5. * @param array $urlList An array of URLs with placeholders. Example: ['https://example.com/{id}', 'https://example.com/{name}']
  6. * @param array $userInput An associative array of user input. Example: ['id' => '123', 'name' => 'JohnDoe']
  7. * @return array An array of URLs with replaced values, or an error message if validation fails.
  8. */
  9. function replaceUrlValues(array $urlList, array $userInput): array
  10. {
  11. $replacedUrls = [];
  12. foreach ($urlList as $url) {
  13. // Basic validation: check if the URL contains placeholders
  14. if (strpos($url, '{') === false || strpos($url, '}') === false) {
  15. $replacedUrls[] = $url; // No placeholders, just add the original URL
  16. continue;
  17. }
  18. $replacedUrl = $url;
  19. $valid = true;
  20. foreach ($userInput as $placeholder => $value) {
  21. // Validate that the placeholder exists in the URL
  22. if (strpos($replacedUrl, '{' . $placeholder . '}') === false) {
  23. return ['error' => "Invalid placeholder: " . $placeholder];
  24. }
  25. // Replace the placeholder with the user input
  26. $replacedUrl = str_replace('{' . $placeholder . '}', $value, $replacedUrl);
  27. }
  28. $replacedUrls[] = $replacedUrl;
  29. }
  30. return $replacedUrls;
  31. }
  32. // Example usage:
  33. $urlList = ['https://example.com/{id}', 'https://example.com/{name}', 'https://example.com/{city}'];
  34. $userInput = ['id' => '456', 'name' => 'JaneSmith'];
  35. $result = replaceUrlValues($urlList, $userInput);
  36. if (isset($result['error'])) {
  37. echo json_encode($result); // Output error message as JSON
  38. } else {
  39. echo json_encode($result); // Output replaced URLs as JSON
  40. }
  41. ?>

Add your comment