PHP preg_replace 补充 link URL 格局
PHP preg_replace supplement link URL pattern
我有以下 URL 结构:
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$/','/demo/?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";
}
帮我改进代码。
您可以使用 parse_url:
if (parse_url($myurl, PHP_URL_HOST) == 'example.com') {
$arr = explode('/', $myurl);
$arr[] = 'demo/' . array_pop($arr) . '?id=test';
$myurl = implode('/', $arr);
}
我有以下 URL 结构:
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$/','/demo/?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";
}
帮我改进代码。
您可以使用 parse_url:
if (parse_url($myurl, PHP_URL_HOST) == 'example.com') {
$arr = explode('/', $myurl);
$arr[] = 'demo/' . array_pop($arr) . '?id=test';
$myurl = implode('/', $arr);
}