我有一个这样的代码:
http://domain.com/link.aspx?r=test5&id=3726&位置=24&子位置=
我想知道如何删除&sublocation=和任何可能在它之后的东西,并使代码看起来像这样:
http://domain.com/link.aspx?r=test5&id=3726&位置=24
我需要为此使用preg_replace函数:
所以我需要这样的东西:
<?php
$host = $_GET['host'];
$ch = curl_init($host);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$response = curl_exec($ch);
curl_close($ch);
echo preg_replace('/<link>(*.?)&sublocation=*<'/link>/', '<link> '$1' </link>', $response);
?>
我只需要一些帮助来修复我编写的preg_replace命令。
感谢
只是一个替代答案。它不使用preg_replace
,只使用substr
和strpos
。
$url = "http://domain.com/link.aspx?r=test5&id=3726&location=24&sublocation=";
$url2 = substr($url, 0, strpos($url, '&sublocation='));
echo $url2;
输出将是
http://domain.com/link.aspx?r=test5&id=3726&location=24
说明:
strpos($url, '&sublocation=')
将返回"&sublocation="字符串的位置。然后使用substr
从0到那个位置,原始字符串将被剪切。
将*
(在&sublocation=*
中)更改为.*
。在正则表达式中,*
的意思是"前面的符号中有0个或多个"。在您的情况下,您有=*
,意思是"0个或多个=符号"。
当您使用.*
时,它意味着"任何字符(换行除外)的0或更多",因为.
意味着"任意字符(换行以外)"*
(*除非输入DOTALL标志(s
))