Can you show us examples?
I know about rawurlencode() and urlencode().
Why do you need to match Chromes encoding?
Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.
Hi guys, I need a way to encode URL before saving it to database but in a way similar to how chrome browser does that where symbols like : / - _ # ... etc, is not encoded unlike rawurlencode() does. is there any package or function would do that ? I have made a lot of searches but found nothing.
There was this solution but still it is a one developer written function and looks like there is still characters that are not preserved but chrome does not encode. https://stackoverflow.com/questions/4929584/encodeuri-in-php
Well this is the best way I found so far for doing this, which is using the following packages to parse the URL and break it to components, then encode each component in the right way depending on the component type. At the end we join encoded components together to form the encoded URL
public function (string $url)
{
$encodedUri = null;
//create new Leage/Uri/Uri instance
$uri = Uri::createFromString($url);
//break the URI into URI components
$scheme = Scheme::createFromUri($uri);
$userInfo = UserInfo::createFromUri($uri);
$host = Host::createFromUri($uri);
$port = Port::createFromUri($uri);
$path = Path::createFromUri($uri);
$query = Query::createFromUri($uri);
$fargment = Fragment::createFromUri($uri);
//create an array of encoded components converted into strings
$components = [
'scheme' => optional($scheme)->getContent(),
'user' => optional($userInfo)->getUser(),
'pass' => optional($userInfo)->getPass(),
'host' => optional($host)->getContent(),
'port' => optional($port)->toInt(),
'path' => optional($path)->getContent(),
'query' => optional($query)->getContent(),
'fragment' => optional($fargment)->getContent()
];
//create an encoded URI from the encoded components
$encodedUri = Uri::createFromComponents($components);
}
//compose URI from the component and return it as one string
return optional($encodedUri)->jsonSerialize();
}
This solution also deals with non english domain names where they are encoded the right way starting with "xn--*" like for example: موقع.com
Would be glade to hear any thoughts related to this solution. Thanks for all participants.
Please or to participate in this conversation.