php - How to get the website name based on whether the website supports http or https?

809

I have links of the following shape:http://website.com/stuff andhttps://website.nl/stuff. I would like to return the http/https part with the website name and domain. So for example, if I have

https://www.stackoverflow.com/questions/55823298/how-do-i-check-if-a-string-is-entirely-made-of-the-same-substring

I would like to returnhttps://www.stackoverflow.com.

if I have

http://www.website.nl/questions/55823298/how-do-i-check-if-a-string-is-entirely-made-of-the-same-substring

I would like to returnhttp://www.website.nl

I now have this very basic code to achieve this:

<?php
$urlData = parse_url('https://www.stackoverflow.com/questions/55823298/how-do-i-check-if-a-string-is-entirely-made-of-the-same-substring');
echo "https://".$urlData['host'];

However, I would like that the code looks at the url and decide which prefix it should be,http orhttps. How can I achieve that?

263

Answer

Solution:

I adjusted my code based on the advice from @RiggsFolly as follows and achieved what I wanted:

<?php
$urlData = parse_url('http://website.nl/questions/55823298/how-do-i-check-if-a-string-is-entirely-made-of-the-same-substring');
echo $urlData['scheme'].'://'.$urlData['host'];

which returnshttp://website.nl as wished.

305

Answer

Solution:

Get the first five characters of the input string and then compare it if it's "https" or http:".

Quoting linked question:

For single-byte strings (e.g. US-ASCII, ISO 8859 family, etc.) use and for multi-byte strings (e.g. UTF-8, UTF-16, etc.) use :

    // singlebyte strings
    $result = substr($myStr, 0, 5);
    // multibyte strings
    $result = mb_substr($myStr, 0, 5);

People are also looking for solutions to the problem: php - WooCommerce Fields Validation on MultiStep Checkout page

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.