匹配 PHP 中 url 中任何带连字符的单词的正则表达式

Regular expression to match any hyphenated word in a url in PHP

我正在尝试用 CloudFront URL 替换 URL。

例如。 URL 可能是

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

然后我将使用:

preg_replace($pattern, $replacement, $string)

我的 $replacement 会是 cloudfront.net/';

这是我目前的 $pattern

^(https?:\/\/)(s3.amazonaws.com)\/(\w+-\w+-\w+)\/(<I want the rest of the url>)

它只会匹配 bucket-with-hyphen 但不会匹配 bucket-with & 我不知道如何捕获其余的 URL.

您可以使用以下方式进行匹配:

(?<=\/)(?:\w+-)+\w+(?=\/)   //no need to capture whole url here

并替换为cloudfront.net

DEMO

这是您更新的正则表达式,它捕获 "bucket"、"bucket-with" 或 "bucket-with-anything",但不会匹配 "bucket-with-something-else"。如果您需要捕获第 4 个选项,请将 {0,2} 更改为 *

我只添加了可选的非捕获组(出现 0 次或 2 次):

^(https?:\/\/)(s3.amazonaws.com)\/(\w+(?:-\w+){0,2})\/(.*)
                                       ^ ^ ^    ^

the regex demo and IDEONE demo