如何在php中格式化URL字符串

时间:2019-02-13 11:54:12

标签: php regex

我正在为我的项目创建路线。为此,我必须格式化一些字符串。我已经通过以下代码做到了这一点,

//Removing unwanted characters
$output = preg_replace( '/[+()^ $%&*~]/', '-', 'This is% my $junk68++ds)(-67url' );

//Removing duplicated dashes
$output = preg_replace('/-+/', '-', $output);

//Removing dashesat the end
if(substr($output,-1)=="-"){
echo substr($output,0,-1);
}else{
echo $output;
};

它可以工作,但我希望有更好的方法可以做到这一点。请问这里有人可以帮助我吗?

1 个答案:

答案 0 :(得分:1)

在样式中添加-,在字符类中添加+量词,然后使用trim删除前导/后跟连字符:

trim(preg_replace( '/[-+()^ $%&*~]+/', '-', 'This is% my $junk68++ds)(-67url' ), '-')
                      ^           ^ 

在字符类的开始/结尾添加连字符时,不必转义。

+量词将匹配与字符类匹配的连续字符的整个块。

请参见regex demolive PHP demo

echo trim( 
    preg_replace( '/[-+()^ $%&*~]+/', '-', '--This is% my $junk68++ds)(-67url-%-' ),
    '-'
);
// => This-is-my-junk68-ds-67url