PHP, remove string using "pattern"
I have the following url which will always have a color variable attached:
http://www.example.com/?new=yes&color=red&shape=square
How would I, using PHP, remove everything at the end; starting at &color, so I开发者_如何学运维 am left with the following:
http://www.example.com/?new=yes
The literal answer to your question is:
$url = substr($url, 0, strpos($url, '&color='));
However, this is good only for the specific case -- it would probably be a good idea to do something a little more robust. For example, splitting the URL, getting the key/value pairs into an array, removing those you don't want (or removing everything except those you want) and recreating the URL.
$url = "http://www.example.com/?new=yes&color=red&shape=square";
$url_parts = explode("&", $url);
$thePartYouWant = $url_parts[0];
I would recommend the combination of parse_url & parse_str. You can also use http_build_url & http_build_str, though these require pecl_http.
精彩评论