如何使用php执行以下操作?
这是我的例子:http://www.example.com/index.php?&xx=okok&yy=no&bb=525252
我想删除这个部分:&yy=no&bb=525252
我只想要这个结果:http://www.example.com/index.php?&xx=okok
我试过这个:
$str = 'bla_string_bla_bla_bla';
echo preg_replace('/bla_/', '', $str, 1); ;
但这不是我想要的。
前往preg_replace是一个良好的开端。但是您需要了解正则表达式。
这将起作用:
$str = 'http://www.example.com/index.php?&xx=okok&yy=no&bb=525252';
echo preg_replace ('/&yy.+$/', '', $str);
这里的正则表达式是&yy.+$
让我们看看这是如何工作的:
&yy
与&yy
明显匹配.+
匹配所有内容$
。。。直到绳子的末端
因此,在这里,我的替换说:将以&yy
开头的内容替换为字符串末尾的内容,不替换为nothing,这实际上只是删除了这一部分。
您可以这样做:
$a = 'http://www.example.com/index.php?&xx=okok&yy=no&bb=525252';
$b = substr($a,0,strpos($a,'&yy')); // Set in '&yy' the string to identify the beginning of the string to remove
echo $b; // Will print http://www.example.com/index.php?&xx=okok
您是否总是希望结束部分具有'yy'变量名?你可以试试这个:
$str = 'http://www.example.com/index.php?&xx=okok&yy=no&bb=525252';
$ex = explode('&yy=', $str, 2);
$firstPart = $ex[0];