php - 将 PHP 中编码 url 的编码部分大写
问题描述
我有这样的字符串网址:
$url = 'htttp://mysite.com/sub1/sub2/%d8%f01'
我想%**
按照示例将 url 的编码部分(仅子字符串) 大写,'%d8%f01'
这样最终的 url 将是:
htttp://mysite.com/sub1/sub2/%D8%F01
可能正在使用preg_replace()
,但无法制作正确的正则表达式。
有什么线索吗?谢谢!!!
解决方案
您可以使用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
推荐阅读
- javascript - 用另一个类属性/方法扩充所有对象
- python - 具有基于装饰器的方法注册表的类
- c# - 使用受约束的泛型将子类型的集合作为基类型的集合返回。编译器无法推断,为什么?
- c++ - 使用标准 C++ 同时迭代 std::vectors
- database - Laravel:: 多台服务器的数据库事务
- java - 使用 JAXB 和 xjc maven 插件生成 Java 类
- javascript - 当找到图像的相对 URL 存储在 cookie 中时,如何从另一个页面检索图像 URL
- loops - 使用 Kotlin 遍历 firebase 数据库
- android - 在泛型类中注入字段
- matlab - smooth filtering shifts my original signal?