简体   繁体   中英

Change URL and append file extension with REGEX

I've been reading up on RegEx docs but I must say I'm still a bit out of my element so I apologize for not posting what I have tried because it was all just plain wrong.

Heres the issue:

I've got images using the following source:

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

I need to get to this:

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

Essentially removing the /.a/ from the URL and appending a .jpg to the end of the image file name. If it helps in a solution I'm using this plug-in: http://urbangiraffe.com/plugins/search-regex/

Thanks All.

This might help you.

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

Online demo

Sample code:

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

Output:

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

Pattern Description:

  (?<=                     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

You can try it without using Positive Lookbehind as well

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

Online demo

Sample code:

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

You can use this:

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

Explanation

  • ([^"]+) matches any characters that are not a " to Group 1
  • \\1 inserts Group 1 in the replacement.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM