首页 > 解决方案 > 将 PHP 中编码 url 的编码部分大写

问题描述

我有这样的字符串网址:

$url = 'htttp://mysite.com/sub1/sub2/%d8%f01'

我想%**按照示例将 url 的编码部分(仅子字符串) 大写,'%d8%f01'这样最终的 url 将是:

htttp://mysite.com/sub1/sub2/%D8%F01

可能正在使用preg_replace(),但无法制作正确的正则表达式。

有什么线索吗?谢谢!!!

标签: phpregex

解决方案


您可以使用preg_replace_callback将匹配%**的子字符串转换为大写:

$url = 'http://example.com/sub1/sub2/%d8%f01';
echo preg_replace_callback('/(%..)/', function ($m) { return strtoupper($m[1]); }, $url);

输出:

http://example.com/sub1/sub2/%D8%F01

请注意,如果并非所有 URL 都经过编码,这也将起作用,例如:

$url = 'http://example.com/sub1/sub2/%cf%81abcd%ce%b5';
echo preg_replace_callback('/(%..)/', function ($m) { return strtoupper($m[1]); }, $url);

输出:

http://example.com/sub1/sub2/%CF%81abcd%CE%B5

更新

也可以直接用 来解决这个问题preg_replace,尽管模式和替换是相当重复的,因为您必须考虑 之后每个位置的所有可能的十六进制数字%

$url = 'http://example.com/sub1/sub2/%cf%81abcd%ce%5b';
echo preg_replace(array('/%a/', '/%b/', '/%c/', '/%d/', '/%e/', '/%f/', 
                        '/%(.)a/', '/%(.)b/', '/%(.)c/', '/%(.)d/', '/%(.)e/', '/%(.)f/'),
                  array('%A', '%B', '%C', '%D', '%E', '%F', 
                        '%$1A', '%$1B', '%$1C', '%$1D', '%$1E', '%$1F'),
                  $url);

输出:

http://example.com/sub1/sub2/%CF%81abcd%CE%5B

更新 2

受到@Martin 的启发,我进行了一些性能测试,该解决方案的运行速度通常比(0.0156 秒对 10000 次迭代的 0.0220 秒)preg_replace_callback快约 25% 。preg_replace


推荐阅读