【问题标题】:preg_replace() Only Specific Part Of Stringpreg_replace() 仅字符串的特定部分
【发布时间】:2013-07-25 08:13:03
【问题描述】:

我总是遇到正则表达式的问题,我基本上有一个url,例如:

http://somedomain.com/something_here/bla/bla/bla/bla.jpg

我需要一个 preg_replace() 来用空字符串替换 something_here,并保留其他所有内容。

我尝试了以下方法,它替换了错误的部分:

$image[0] = preg_replace('/http:\/\/(.*)\/(.*)\/wp-content\/uploads\/(.*)/','$2' . '',$image[0]);

这最终只留下了我想要替换的部分,而不是实际替换它!

【问题讨论】:

  • 为此使用parse_url() 并在路径部分进行替换。

标签: php regex replace preg-replace


【解决方案1】:

以下代码基于您提供的描述:

$url = 'http://somedomain.com/something_here/bla/bla/bla/bla.jpg';
$output = preg_replace('#^(https?://[^/]+/)[^/]+/(.*)$#', '$1$2', $url);
echo $output; // http://somedomain.com/bla/bla/bla/bla.jpg

说明:

  • ^ : 匹配行首
  • ( : 开始匹配组 1
    • https?:// : 匹配 http 或 https 协议
    • [^/]+ :匹配除/ 之外的任何内容一次或多次
    • / : 匹配 /
  • ) : 结束匹配组 1
  • [^/]+ :匹配除/ 之外的任何内容一次或多次 -/:匹配/
  • ( : 开始匹配组 2
    • .* :匹配任何东西零次或多次(贪婪)
  • ) : 结束匹配组 2
  • $ : 匹配行尾

【讨论】:

    【解决方案2】:

    你可以这样做:

    $image[0] = preg_replace('!^(http://[^/]*)/[^/]*!', '$1', $image[0]);
    

    或者您可以考虑只拆分字符串以处理其各个组件:

    $parts = explode('/', $image[0]);
    unset($parts[3]);
    $image[0] = implode('/', $parts);
    

    【讨论】:

      【解决方案3】:

      您可以通过简单的字符串替换来做到这一点:

      $image[0] = str_replace('/wp-content/uploads/', '/', $image[0]);
      

      或者如果你想使用正则表达式:

      $image[0] = preg_replace('~(http://.*?)/wp-content/uploads/(.*)~', '$1/$2', $image[0]);
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2016-12-16
        • 1970-01-01
        • 1970-01-01
        • 2015-12-29
        • 1970-01-01
        • 2022-06-27
        • 1970-01-01
        相关资源
        最近更新 更多