regex to replace string with params

北城余情 提交于 2019-12-13 08:52:26

问题



Please help me to create regex for replace a string like:
/technic/k-700/?type=repair
to a string like
/repair/k-700/
Instead of k-700 can be any another combination (between / ) and instead of repair can be only kit.
I need pattern and replacement, please. It's so hard for me.
My result not working for Wordpress:

$pattern = '/technic/([0-9a-zA-Z-]+)/?type=$matches[1]';
$replacement = '/?/([0-9a-z-]+)/';

回答1:


You can try something like this:

$test = preg_replace(
    '~/\w+/([\w-]+)/\?type=(\w+)~i',
    '/$2/$1/',
    '/technic/k-700/?type=repair'
);
var_dump($test);

The result will be:

string(14) "/repair/k-700/"



回答2:


You don't need regex, you can do it simply by using explode():

$str = '/technic/k-700/?type=repair';
$first = explode('/', explode('?', $str)[0]);
$second = explode('=', explode('?', $str)[1]);
$first[1] = $second[1];
echo $new = implode("/",$first);

//output: /repair/k-700/



回答3:


For the sake of completeness or if you need to access the url parts later.
Here's a solution using parse_url and parse_str

$str = '/technic/k-700/?type=repair';

$url = parse_url($str);

$bits = explode('/',trim($url['path'],'/'));

parse_str($url['query']);

print '/' . $type . '/' . $bits[1] . '/' ;

Which will output

/repair/k-700/


来源:https://stackoverflow.com/questions/35627926/regex-to-replace-string-with-params

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!