更改URL并使用REGEX附加文件扩展名


Change URL and append file extension with REGEX

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

问题在这里:

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

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

我需要得到这个:

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

去掉/。a/从URL,并在图像文件名的末尾附加一个。jpg。如果它在解决方案中有帮助,我使用这个插件:http://urbangiraffe.com/plugins/search-regex/

谢谢。

这可能对你有帮助。

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

在线演示

示例代码:

$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'/([^"]*)

在线演示

示例代码:

$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);

你可以这样做:

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

  • ([^"]+)匹配任何非"到组1
  • '1在替换组中插入组1