在 PHP 7.4 中,针对 URI ,基于 league/uri 添加查询参数
1、在 Laravel 6 中,基于判断字符串中是否包含 ?,有一个简单的实现
use Illuminate\Support\Str; if (Str::contains($themeAwareUrlPath, '?')) { $suffix = '&'; } else { $suffix = '?'; } return new HtmlString($prefix.$themeAwareUrlPath.$suffix.'d='.config('app.url'));
2、不过此实现,一些复杂的 URI 未考虑到。例:?d=3&e=5#6,会被替换为:?d=3&e=5#6&d=https://xxx.com 。
3、最终决定基于 league/uri 添加查询参数,执行 composer require league/uri-components、composer require league/uri
4、代码实现如下
use League\Uri\Uri; use League\Uri\UriModifier; $uri = Uri::createFromString($themeAwareUrlPath); $cdnUri = UriModifier::mergeQuery($uri, 'd=' . config('app.url')); return new HtmlString($prefix . $cdnUri->jsonSerialize());
5、基于一些常见的 URI ,替换后的结果如下,符合预期
$themeAwareUrlPath = '9919b10c-9217-44eb-8488-198a321067cc/assets/images/default-banner.64bbdd.jpg'; $themeAwareUrlPath .= '?a=3'; string(102) "9919b10c-9217-44eb-8488-198a321067cc/assets/images/default-banner.64bbdd.jpg?a=3&d=https://xxx.local" $themeAwareUrlPath .= '?d=3'; string(98) "9919b10c-9217-44eb-8488-198a321067cc/assets/images/default-banner.64bbdd.jpg?d=https://xxx.local" $themeAwareUrlPath .= '?d=3&e=5#6'; string(104) "9919b10c-9217-44eb-8488-198a321067cc/assets/images/default-banner.64bbdd.jpg?d=https://xxx.local&e=5#6" $themeAwareUrlPath .= '?a=1&d=3&e=5#6'; string(108) "9919b10c-9217-44eb-8488-198a321067cc/assets/images/default-banner.64bbdd.jpg?a=1&d=https://xxx.local&e=5#6" $themeAwareUrlPath .= '?#'; string(100) "9919b10c-9217-44eb-8488-198a321067cc/assets/images/default-banner.64bbdd.jpg?&d=https://xxx.local#" $themeAwareUrlPath .= '?'; string(99) "9919b10c-9217-44eb-8488-198a321067cc/assets/images/default-banner.64bbdd.jpg?&d=https://xxx.local"
近期评论