preg replace - PHP preg_replace supplement link URL pattern -
i have following urls structure:
http://example.com/item/example-descriptions/6454986 http://example.com/item/example-bla-bla-bla/6545455 http://example.com/item/example-other-url/5454555
i need add text numbers (add "/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
here couple of ways imperfect:
$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"; }
and
$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"; }
help me improve code.
you can use parse_url:
if (parse_url($myurl, php_url_host) == 'example.com') { $arr = explode('/', $myurl); $arr[] = 'demo/' . array_pop($arr) . '?id=test'; $myurl = implode('/', $arr); }
Comments
Post a Comment