PHP preg_replace补充链接URL模式

时间:2015-04-01 13:33:45

标签: preg-replace explode

我有以下网址结构:

http://example.com/item/example-descriptions/6454986
http://example.com/item/example-bla-bla-bla/6545455
http://example.com/item/example-other-url/5454555

我需要在数字中添加文字才能获得(添加" / demo /""?id = test")

http://example.com/item/example-descriptions/demo/6454986?id=test
http://example.com/item/example-bla-bla-bla/demo/6545455?id=test
http://example.com/item/example-other-url/demo/5454555?id=test

以下几种方法不完美:

$myurl = 'http://example.com/item/example-descriptions/6454986';

    if (substr_count($myurl, 'example.com')){
    $url = "$myurl.html";   
    $url = preg_replace('/^(.*)\/([^.]+)\.html$/','$1/demo/$2?id=test', $url); 

    echo "$url";
    } else {  
    echo "$myurl";
}

$myurl = 'http://example.com/item/example-descriptions/6454986';

    if (substr_count($myurl, 'example.com')){
        $url = explode('/', $myurl);  

echo "" . $url[0] . "/" . $url[1] . "/" . $url[2] . "/" . $url[3] . "/" . $url[4] . "/demo/" . $url[5] . "/?id=test";

    } else {  
    echo "$myurl";
}

帮助我改进代码。

1 个答案:

答案 0 :(得分:0)

您可以使用parse_url

if (parse_url($myurl, PHP_URL_HOST) == 'example.com') {
    $arr = explode('/', $myurl);
    $arr[] = 'demo/' . array_pop($arr) . '?id=test';
    $myurl = implode('/', $arr);
}