0

I'm a beginner in PHP. And would need help in resolving the following issue.

This is the the original string

/hs/?page_id=27&file=filename.jpg

And i would like it to be replaced with the following.

/hs/wp-content/gallery/filename.jpg

And please note that the filename and id number are subjected to change everytime. So i guess use of wildcards could be a better choice to replace the characters between "?" and "=" .

How could this be accomplished with the use of reg_replace ? Or is there any other solution ?

4

2 回答 2

1

如果您想避免使用正则表达式,可以使用PHPparse_url和函数:parse_str

$url= '/hs/?page_id=27&file=filename.jpg';
$parsed = parse_url($url); 
parse_str($parsed['query'], $query);

$new_url = $parsed['path'] . 'wp-content/gallery/' . $query['file'];

Ideone 演示。

于 2013-09-19T18:00:45.230 回答
0

替换?and之间的字符的最简单方法=是使用.*正则表达式部分,它将匹配“任何内容,重复任意次数”

$result = preg_replace('[/hs/\?.*=]', '/hs/wp-content/gallery/', $input);

如果要提取file=任何输入 URL 的组件,即使参数的顺序不同,更通用的解决方案是:

$result = preg_replace('[.*file=([^&]*).*]', '/hs/wp-content/gallery/\1', $input);
于 2013-09-19T16:29:49.173 回答