修剪字符串中的字符

Given the following URL:

http://www.domain.com/reporting/category-breakdown.php?re=updated

I need to remove everything after the .php

It might be "?re=updated" or it could be something else. The number of characters won't always be the same, the string will always end with .php though.

How do I do this?

To find the first position of a substring in a string you can use strpos() in PHP.

$mystring = 'http://www.domain.com/reporting/category-breakdown.php?re=updated';
$findme   = '.php';
$pos = strpos($mystring, $findme);

After, you have the position of the first character of your substring '.php' in your URL. You want to get the URL until the end of '.php', that means the position you get + 4 (substring length). To get this, you can use substr(string,start,length) function.

substr($mystring, 0, $pos + 4);

Here you are!

Find the first indexOf (".php"), then use substring from char 0 to your index + the length of (".php");

3 line solution:

$str = "http://www.domain.com/reporting/category-breakdown.php?re=updated";
$str = array_shift(explode('?', $str));
echo $str;

Note: it's not fool-proof and could fail in several cases, but for the kind of URLs you mentioned, this works.

Here is another way to get the non-query-string part of a url with PHP:

$url = 'http://www.domain.com/reporting/category-breakdown.php?re=updated';
$parsed = parse_url($url);
$no_query_string = $parsed['scheme'] . '://' . $parsed['hostname'] . $parsed['path'];
// scheme: http, hostname: www.domain.com, path: /reporting/category-breakdown.php

That will handle .php, .phtml, .htm, .html, .aspx, etc etc.

Link to Manual page.