仅删除 url/string 中的第一个斜线

delete only first slashes from url/string

我想删除字符串的前两个斜杠。

//cdn.klingel.de/images/100/3/7/1/5/0/8/371508F1.jpg

之后我想包括 http:// 新的。但这不是问题。

str_replace 替换所有斜杠...

信息:

我有不同的字符串。示例:

/media/images/CmsPageModuleDataItem/62/6260.0_gefro-suppennudeln.jpg

//cdn.abc.de/images/100/3/7/1/5/0/8/371508F1.jpg

http://s7.abc.com/is/image/LandsEnd/461469_FG16_LF_616

我需要在这些 url 前加一个正确的 http://

也许有人知道一个聪明的解决方案。

谢谢。

一种有效的方法是使用 parse_url 并逐个重建 url:

$urls = [
    '/media/images/CmsPageModuleDataItem/62/6260.0_gefro-suppennudeln.jpg',
    '//cdn.abc.de/images/100/3/7/1/5/0/8/371508F1.jpg',
    'http://s7.abc.com/is/image/LandsEnd/461469_FG16_LF_616',
    'toto',
    'example.com/path?a=1&b=2#anchor'
];

$results = [];

define ('DEFAULT_SCHEME', 'http');
define ('DEFAULT_HOST', 'default.host.com');

foreach ($urls as $url) {
   $parts = parse_url($url);

   $results[] = (isset($parts['scheme']) ? $parts['scheme'] : DEFAULT_SCHEME) . '://'
              . (isset($parts['host'])? $parts['host'] : DEFAULT_HOST)
              . '/' . ltrim($parts['path'], '/')
              . (isset($parts['query']) ? '?' . $parts['query'] : '')
              . (isset($parts['fragment']) ? '#' . $parts['fragment'] : '');
}

print_r($results);

demo

您可以使用爆炸功能:

<?php
    $str = "//cdn.klingel.de/images/100/3/7/1/5/0/8/371508F1.jpg";
    $array= explode("/",$str);
?>

然后你可以做一个forloop把数组放回字符串。

http://www.w3schools.com/php/func_string_explode.asp

希望这就是您要找的。

$str = "//Hello World/theEnd!";
echo $str . "<br>";
$str = trim($str,"/");
$str = "http://" . $str; 
echo $str;

给你http://Hello World/theEnd!

如果你想花哨一点,你也可以把它也当作一个循环。

function addhttp($url) {
$url = trim($url,"/");

if (!preg_match("~^(?:f|ht)tps?://~i", $url)) {
    $url = "http://" . $url;
}
return $url;

}

$add = "/media/images/CmsPageModuleDataItem/62/6260.0_gefro-suppennudeln.jpg";
$add1 = "//cdn.abc.de/images/100/3/7/1/5/0/8/371508F1.jpg";
$add2 = "http://s7.abc.com/is/image/LandsEnd/461469_FG16_LF_616";
echo "<br />"; 

echo addhttp($add); 
echo "<br />"; 
echo addhttp($add1); 
echo "<br />"; 
echo addhttp($add2); 

这给你

http://media/images/CmsPageModuleDataItem/62/6260.0_gefro-suppennudeln.jpg
http://cdn.abc.de/images/100/3/7/1/5/0/8/371508F1.jpg
http://s7.abc.com/is/image/LandsEnd/461469_FG16_LF_616

另一种选择是为此使用正则表达式:

^((http:)?(\/){1,2}).*

这是一个 regex101 fiddle:
https://regex101.com/r/lUXTDf/1

这是 php using preg_replace 中的用法:

var_dump(preg_replace('/^(?:(?:http:)?(?:\/){1,2})(.*)/', 'http://', $s1));

http://sandbox.onlinephpfunctions.com/code/b49af5519e8a7a4e47baffa9a8a7199c3bddbd42

@cgee use ltrim() function it will trim left side means you starting string's / or // both just look try the below one

<?php
    $preString = "http://";
    $s1 = "/media/images/CmsPageModuleDataItem/62/6260.0_gefro-suppennudeln.jpg";
    $s2 = "//cdn.abc.de/images/100/3/7/1/5/0/8/371508F1.jpg";
    echo $preString.ltrim($s1, '/');
    echo "<br>";
    echo $preString.ltrim($s2, '/');
?>