w3resource
w3resource logo

PHP Exercises : Return url components

(追記) (追記ここまで)
(追記) (追記ここまで)

8. Parse URL Components

Write a PHP script, which will return the following components of the url 'https://www.w3resource.com/php-exercises/php-basic-exercises.php'.

List of components : Scheme, Host, Path

What is a URL?

URL stands for Uniform Resource Locator. It is used to specify its location on a computer network and a mechanism for retrieving it. A URL is the fundamental network identification for any resource connected to the web (e.g., hypertext pages, images, and sound files).

URLs have the following format:

protocol://hostname/other_information

For example, the URL for w3resource's PHP basic exercises page is:

'https://www.w3resource.com/php-exercises/php-basic-exercises.php';

Sample Solution:

PHP Code:

<?php
// Define the URL to be parsed
$url = 'https://www.w3resource.com/php-exercises/php-basic-exercises.php';
// Parse the URL and store its components in the $url variable
$url = parse_url($url);
// Display the scheme (protocol) of the parsed URL
echo 'Scheme : ' . $url['scheme'] . "\n";
// Display the host (domain) of the parsed URL
echo 'Host : ' . $url['host'] . "\n";
// Display the path of the parsed URL
echo 'Path : ' . $url['path'] . "\n";
?>

Sample Output:

Scheme : http 
Host : www.w3resource.com 
Path : /php-exercises/php-basic-exercises.php

Explanation:

Here's a brief explanation of the above exercise:

  • $url = 'https://www.w3resource.com/php-exercises/php-basic-exercises.php';
    • Defines a URL string to be parsed.
  • $url = parse_url($url);
    • Parses the defined URL using the "parse_url()" function and stores the components (scheme, host, path, etc.) in the '$url' variable.
  • echo 'Scheme : ' . $url['scheme'] . "\n";
    • Displays the scheme (protocol) of the parsed URL.
  • echo 'Host : ' . $url['host'] . "\n";
    • Displays the host (domain) of the parsed URL.
  • echo 'Path : ' . $url['path'] . "\n";
    • Displays the path of the parsed URL.

Flowchart:

Flowchart: Return some components of an url

For more Practice: Solve these Related Problems:

  • Write a PHP script to extract and display query parameters from a complex URL string.
  • Write a PHP script to deconstruct a URL into its components and then reconstruct it manually.
  • Write a PHP script to validate the URL structure and output each component on a separate line.
  • Write a PHP script to detect changes in URL components after adding or removing query strings.


Go to:


PREV : Get Current File Name.
NEXT : Change Color of First Character.

PHP Code Editor:



Have another way to solve this solution? Contribute your code (and comments) through Disqus.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.

(追記) (追記ここまで)


(追記) (追記ここまで)
(追記) (追記ここまで)


AltStyle によって変換されたページ (->オリジナル) /