【问题标题】:Change URL and append file extension with REGEX使用 REGEX 更改 URL 并附加文件扩展名
【发布时间】:2014-07-11 21:15:38
【问题描述】:

我一直在阅读 RegEx 文档,但我必须说我仍然有点脱离我的元素,所以我很抱歉没有发布我尝试过的内容,因为这完全是错误的。

问题来了:

我有使用以下来源的图像:

src="http://samplesite/.a/6a015433877b2b970c01a3fd22309b970b-800wi"

我需要解决这个问题:

src="http://newsite.com/wp-content/uploads/2014/07/6a015433877b2b970c01a3fd22309b970b-800wi.jpg"

基本上从 URL 中删除 /.a/ 并将 .jpg 附加到图像文件名的末尾。如果它有助于解决我正在使用这个插件:http://urbangiraffe.com/plugins/search-regex/

谢谢大家。

【问题讨论】:

标签: php regex


【解决方案1】:

这可能会对你有所帮助。

(?<=src="http:\/\/)samplesite\/\.a\/([^"]*)

Online demo

示例代码:

$re = "/(?<=src=\"http:\/\/)samplesite\/\.a\/([^\"]*)/";
$str = "src=\"http://samplesite/.a/6a015433877b2b970c01a3fd22309b970b-800wi\"";
$subst = 'newsite.com/wp-content/uploads/2014/07/$1.jpg';

$result = preg_replace($re, $subst, $str);

输出:

src="http://newsite.com/wp-content/uploads/2014/07/6a015433877b2b970c01a3fd22309b970b-800wi.jpg"

模式说明:

  (?<=                     look behind to see if there is:
    src="http:               'src="http:'
    \/                       '/'
    \/                       '/'
  )                        end of look-behind

  samplesite               'samplesite'
  \/                       '/'
  \.                       '.'
  a                        'a'
  \/                       '/'

  (                        group and capture to \1:
    [^"]*                    any character except: '"' (0 or more
                             times (matching the most amount
                             possible))
  )                        end of \1

你也可以不使用Positive Lookbehind试试

(src="http:\/\/)samplesite\/\.a\/([^"]*)

Online demo

示例代码:

$re = "/(src=\"http:\/\/)samplesite\/\.a\/([^\"]*)/";
$str = "src=\"http://samplesite/.a/6a015433877b2b970c01a3fd22309b970b-800wi\"";
$subst = '$1newsite.com/wp-content/uploads/2014/07/$2.jpg';

$result = preg_replace($re, $subst, $str);

【讨论】:

  • 感谢您的解释和示例,现在对我来说更有意义了!
【解决方案2】:

你可以用这个:

$replaced = preg_replace('~src="http://samplesite/\.a/([^"]+)"~',
                 'src="http://newsite.com/wp-content/uploads/2014/07/\1.jpg"',
                  $yourstring);

说明

  • ([^"]+) 将任何不是" 的字符匹配到组 1
  • \1 在替换中插入第 1 组。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-07-12
    • 2015-10-04
    • 1970-01-01
    • 2016-06-17
    • 2017-04-30
    • 1970-01-01
    • 2013-08-28
    相关资源
    最近更新 更多