I'm trying to replace a URL with CloudFront URL.
For example. the URL could be
https://s3.amazonaws.com/bucket/folder/d05c229a73b5c6f169d599652015b1.png
https://s3.amazonaws.com/bucket-with-hyphen/folder/folder1/d05c229a73b5c6f169d599652015b1.png
https://s3.amazonaws.com/bucket-with-hyphen/folder-with-hyphen/folder1/d05c229a73b5c6f169d599652015b1.png
And then I'll use:
preg_replace($pattern, $replacement, $string)
My $replacement
would be $1cloudfront.net/$4';
Here's my $pattern
so far
^(https?:\/\/)(s3.amazonaws.com)\/(\w+-\w+-\w+)\/(<I want the rest of the url>)
It will only match bucket-with-hyphen
but not bucket-with
& I don't know how to capture the rest of the URL.
Here is your updated regex that captures "bucket", "bucket-with" or "bucket-with-anything", but won't match "bucket-with-something-else". If you need to capture the 4th option, change {0,2}
to *
.
I only added optional non-capturing groups (0 or 2 occurrences):
^(https?:\/\/)(s3.amazonaws.com)\/(\w+(?:-\w+){0,2})\/(.*)
^ ^ ^ ^
See the regex demo and IDEONE demo
You can use the following to match:
(?<=\/)(?:\w+-)+\w+(?=\/) //no need to capture whole url here
And replace with cloudfront.net
See DEMO
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.