31 January 2024

There are 2 methods you can use for this. The parse_url method involves breaking down the URL into components using PHP's built-in function, allowing for selective extraction of the scheme, host, and path. This approach provides flexibility, making it suitable for scenarios where specific URL components need to be manipulated. On the other hand, the strtok method utilizes tokenization to swiftly extract the portion of the URL before the first occurrence of a specified delimiter ('?'). This approach is concise and particularly well-suited for straightforward cases where the primary objective is to remove query parameters without the need for detailed manipulation of individual components.

Source code viewer
  1. /**
  2.  * parse_url Approach:
  3.  */
  4. // Your original URL
  5. $originalUrl = "http://example.com/page?param1=value1&param2=value2";
  6.  
  7. // Parse the URL
  8. $parsedUrl = parse_url($originalUrl);
  9.  
  10. // Reconstruct the URL without query parameters
  11. $strippedUrl = $parsedUrl['scheme'] . '://' . $parsedUrl['host'] . $parsedUrl['path'];
  12.  
  13. // Output the result
  14. echo $strippedUrl;
  15.  
  16. /**
  17.  * strtok Approach:
  18.  */
  19. // Your original URL
  20. $originalUrl = "http://example.com/page?param1=value1&param2=value2";
  21.  
  22. // Use strtok to get the scheme and host
  23. $strippedUrl = strtok($originalUrl, "?");
  24.  
  25. // Output the result
  26. echo $strippedUrl;
Programming Language: PHP