Jimmy J.
Jimmy J.

Reputation: 1

Add http:// prefix to URL when it is missing

Hello Guys im using this to Add http:// prefix to Url when missing. The problem is that he add it to the other Url's where i have http:// already.

foreach($result as $key => &$value)
    {

        if  (strpos($sample['Internetadress'], 'http://') === false){
            $sample['Internetadress'] = 'http://' .$sample['Internetadress'];
            }

    }
  1. i want that he doesnt edit it when it exist.
  2. i want that he doesnt add it when there is no URL.

Sorry about my english im from Germany :D

Upvotes: 0

Views: 1154

Answers (2)

I think in this case a little regex is a good solution:

$urls = [
    'http://www.example.com',
    'foo.bar.com',
    'https://example.com',
    'www.example.com'
];

foreach ($urls as &$url) {
    $url = preg_replace('/^(?!http)/i', 'http://', $url);
}

The values in $urls after the loop are:

[
    "http://www.example.com",
    "http://foo.bar.com",
    "https://example.com",
    "http://www.example.com"
]

Also instead of using a foreach loop and passing the values by reference you could use a array_map() like this:

$urls = array_map(function($url) {
    return preg_replace('/^(?!http)/i', 'http://', $url);
}, $urls);

Upvotes: 0

pr1nc3
pr1nc3

Reputation: 8338

Your code shoud cover your first point (when http exist don't change the URL), if not provide us a sample url that you want to modify.

For the second point you just make another check like this:

<?php
$sample['Internetadress']='www.example.com';

if  (strpos($sample['Internetadress'], 'http://') === false && trim($sample['Internetadress'])!==''){
    if(strpos($sample['Internetadress'], 'https://') === false){
        $sample['Internetadress'] = 'http://' .$sample['Internetadress'];
    }
}


echo $sample['Internetadress'];

Upvotes: 1

Related Questions