【问题标题】:Insert slash at specific place in string with preg_replace使用 preg_replace 在字符串中的特定位置插入斜杠
【发布时间】:2015-01-13 14:41:51
【问题描述】:

我正在尝试编写一个函数,该函数将在损坏的 URL 中插入一个反斜杠,由于某种原因,该 URL 在 http 之后缺少第二个反斜杠,我只想返回固定版本,例如

 addSlash(http:/example.net) ->  http://example.net
 addSlash(https:/example.net`) -> https://example.net

我认为这可以通过 preg_replace 在一行代码中解决,但我无法让它工作。使用 $url = 'http:/example.net' 和

preg_replace("@^(https?:)(.*?)@", "\1/\2", $url);

我回来/ /example.net,好像'http'不匹配并放入\1。

有什么建议吗?如果可能的话,我想避免回调和匿名函数,因为这应该在旧版本的 PHP 上运行。

【问题讨论】:

    标签: php preg-replace


    【解决方案1】:
    /^(https:|http:)?[\\/](?![\\/])(.*)/
    

    类似的东西应该work 给你。

    $re = "/^(https:|http:)?[\\/](?![\\/])(.*)/mi"; 
    $str = "https:/regex101.com\nhttp:/regex101.com\nhttps://regex101.com"; 
    
    $result = preg_replace($re, '$1//$2' , $str);
    
    var_dump($result);
    

    【讨论】:

    • 你用 php 测试过吗?我只是运行代码,我得到了和以前几乎一样的结果
    • 抱歉,更新了代码,刚刚测试过,对我有用。
    【解决方案2】:

    这应该可行:

    preg_replace('@^(https*:)(/.*)@', '\1/\2', $url);
    

    甚至:

    preg_replace('@^(https*:)@', '\1/', $url);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-05-10
      • 2012-12-01
      • 1970-01-01
      • 1970-01-01
      • 2022-07-08
      • 2021-09-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多