准备
最近有一个任务,需要对Url进行加参数的传递,但是参数需要有指定的数据补充,不能提前写死。因此,准备使用正则替换的方式实现此功能。
php函数
# 执行一个全局正则表达式匹配
preg_match_all
preg_match_all(
string $pattern,
string $subject,
array &$matches = null,
int $flags = 0,
int $offset = 0
): int|false|null
// 搜索subject中所有匹配pattern给定正则表达式 的匹配结果并且将它们以flag指定顺序输出到matches中.
// 在第一个匹配找到后, 子序列继续从最后一次匹配位置搜索.
成果
$ssss = ['id'=>1,'php'=>5,'php1'=>7];
$page = "index/php?id=id&php=php&php1=php1";
preg_match_all("/(\w+=(?P<name>\w+))(#\w+)?/i",$page,$match);
if(!empty($match) and isset($match['name'])){
$names = $match['name'];
foreach($names as $name){
$page = str_replace('='.$name,'='.$ssss[$name],$page);
}
}
补充
(?P<name>\w+)
的意思就是命名一个名字为name的组,匹配规则符合后面的/w+
本文作者:Fly
本文链接:https://www.xuehuafei.cn/archives/regular-replacement-url-placeholder-paramete.html
版权声明:白嫖注明出处