我有一个网址&它的结构如
https://www.example.com/i/location-name/category/subcategory/item/item-id
我想使用PHP通过新参数动态替换url参数( location-name )。
修改后的网址看起来像这样
https://www.example.com/i/new-parameter/category/subcategory/item/item-id
我使用http_build_query();
成功完成了查询参数但是在这种情况下,我曾尝试使用preg_replace(),但它不能正常工作
由于
答案 0 :(得分:2)
如果您想使用正则表达式。
$url = 'https://www.example.com/i/location-name/category/subcategory/item/item-id';
$new_param = 'new-parameter';
print preg_replace('|/location-name/|','/'.$new_param.'/',$url);
我不建议只搜索位置名称(不带斜杠),因为它会匹配例如位置名称字符串。
<强>更新强>
根据展示位置而不是字符串,您可以通过以下方式更改该部分:
$url = 'https://www.example.com/i/location-name/category/subcategory/item/item-id';
$new_param = 'new-parameter';
$new_url = preg_replace('|/i/(.*?)/|','/i/'.$new_param.'/',$url);
print $new_url.'<br/>';
$new_param = 'another-parameter';
$new_url = preg_replace('|/i/(.*?)/|','/i/'.$new_param.'/',$url);
print $new_url.'<br/>';
你会得到:
https://www.example.com/i/new-parameter/category/subcategory/item/item-id
https://www.example.com/i/another-parameter/category/subcategory/item/item-id
替代解决方案 如果你想确定改变,你可以采取另一种方式,例如:
$url = 'https://www.example.com/i/location-name/category/subcategory/item/item-id';
$new_param = 'new-param';
$parts = parse_url($url);
$path_parts = explode('/',$parts['path']);
$path_parts[2] = $new_param;
$new_path = implode('/',$path_parts);
$new_url = $parts['scheme'].'://'.$parts['host'].$new_path;
print( $new_url);
答案 1 :(得分:1)
试试这个:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Type something in the input field, scroll down, and type again.<br>
The page scrolls up to the input again, I want to avoid it.<br>
<input type="text" class="search">
<br>