【问题标题】:Replace http or https prefix in string PHP [duplicate]替换字符串 PHP 中的 http 或 https 前缀 [重复]
【发布时间】:2018-09-03 05:16:00
【问题描述】:

我有一个 php 变量,其中包含这样的 url 字符串:

$url1 = 'http://test1.com/';
$url2 = 'https://test2.com';
$url3 = 'http://test3.com/';

我想用特定字符串替换 http 或 https 前缀,并且仅当字符串变量在字符串末尾包含破折号时才删除末尾的破折号,例如:

$url1 = 'stackoverflow://test1.com';
$url2 = 'stackoverflow://test2.com';
$url3 = 'stackoverflow://test3.com';

【问题讨论】:

  • 你有没有尝试过?分享您的代码。
  • @EmptyBrain 不,我不知道该怎么做
  • @EmptyBrain 快捷方式https?
  • echo preg_replace ('/https|http/','stackoverflow','http://test1.com/');
  • @EmptyBrain 如果我有这样的 url https://sdasdahttpol.com/ 它将替换 https 之后的 http,以及如何删除最后一个字符串字符中的 / 如果只有字符串最后一个字符是 @987654327 @

标签: php regex string


【解决方案1】:

你可以试试:

$test = "https://stackoverflow.com/";
$test = rtrim(preg_replace ('/https|http/','test',$test,1),'/');
echo $test;

【讨论】:

  • 如果我有这样的网址https://sdasdahttpol.com/ 它将替换 https 之后的 http,
  • @TinyDancer 检查更新的答案
【解决方案2】:

你可以使用str_replace来解决这个问题,

 $url = rtrim(str_replace(['http://', 'https://', ], 'stackoverflow://', $url), '/');

【讨论】:

    【解决方案3】:

    试试

    $url1 = 'http://test1.com/';   
    echo str_replace(['http://', 'https://'],'',$url1);
    

    【讨论】:

      【解决方案4】:

      试试这个

      echo reConstructUrl('http://test1.com/','stackoverflow');
      function reConstructUrl($url,$replace_string){
        return  rtrim(preg_replace ('/https|http/',$replace_string,$url),'/');
      }
      

      【讨论】:

        猜你喜欢
        • 2012-10-22
        • 2021-06-25
        • 2023-03-24
        • 2014-06-12
        • 2017-04-03
        • 1970-01-01
        • 2020-09-14
        • 2021-03-20
        • 2011-10-10
        相关资源
        最近更新 更多