1. In Laravel 6, there is a simple implementation based on checking whether the string contains ?
PHP
use Illuminate\Support\Str;
if (Str::contains($themeAwareUrlPath, '?')) {
$suffix = '&';
} else {
$suffix = '?';
}
return new HtmlString($prefix.$themeAwareUrlPath.$suffix.'d='.config('app.url'));
2. However, this implementation does not account for some complex URIs. For example: ?d=3&e=5#6 would be replaced with: ?d=3&e=5#6&d=https://xxx.com .
3. I ultimately decided to add query parameters based on league/uri, executing composer require league/uri-components and composer require league/uri.
4. The code implementation is as follows:
PHP
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. Based on some common URIs, the replacement results are as follows, meeting expectations:
Plaintext
$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"
