PHP 从$string获取零件


PHP Get a part from $string

你能帮我解析字符串吗?

字符串为:

$str = 'http://test.al/admin/?plugin=pages&act=delete&file=test-page';

它是动态的,可以包含更多 &-符号。

我想得到除"&..."开头的部分之外的所有内容所以结果应该是:

http://boot.al/admin/?plugin=pages

删除文件后需要它返回,以清除额外的 $_GET 参数。

提前谢谢你!

使用 strtok()

<?php
$str = 'http://test.al/admin/?plugin=pages&act=delete&file=test-page';
$result = strtok($str, '&');
var_dump($result); // outputs "http://test.al/admin/?plugin=pages"
$parts = explode('&', $str);
$str = $parts[0];

通过使用&作为分隔符将字符串转换为数组。数组的第一个元素将保存您需要的部分

为此使用parse_url()

$str = 'http://test.al/admin/?plugin=pages&act=delete&file=test-page';
$url_components = parse_url($str);
$get_component = explode("&", $url_components['query']);
$new_str = $url_components['scheme'] . "://" . $url_components['host'] . $url_components['path'] . "?" . $get_component[0];
echo $new_str;

输出:

http://test.al/admin/?plugin=pages