Reputation: 1
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'];
}
}
Sorry about my english im from Germany :D
Upvotes: 0
Views: 1154
Reputation: 71
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
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