Is there a php string function to trim a string after a particular character. I had a look on the php.net site and did a google search but couldn\'t find anything. The only
You could use explode:
$string = "/gallery/image?a=b";
list($url,$querystring) = explode('?', $string, 2);
The strstr
and stristr
functions finds the first occurrence in a string and returns everything after it (including the search string). But it you supply true
as the third argument, it brings back everything in front of the search string.
$string = strstr( $string, '?', true); # Returns /gallery/image
If the match is not found it returns FALSE
so you could write an error check like this:
if( $path = strstr( $string, '?', true) ){
# Do something
}
Although pure string functions may give better performance, this is not just a string; it's a URI. Therefore it makes more sense to use a function that's made to handle such data:
echo parse_url("/gallery/image?a=b", PHP_URL_PATH);
// Output: /gallery/image
This may be overkill for what you are trying to do, but if you want to break apart a URL into pieces, try the PHP function parse_url
. Here's the PHP manual page.
You'd then want the "path" portion of the resulting array.
Maybe something like this:
$string = substr($string, 0, strpos($string, '?'));
Note that this isn't very robust (i.e. no error checking, etc), but it might help you solve your problem.
function imaginary_function($string, $char) {
$index = strpos($char, $needle);
if ($index === false) { return $string };
return substr($string, 0, $index);
}
An excellent, official list of string manipulation functions is available here.