Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Php trim string at a particular character

Tags:

string

php

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 solution I could think of was explode and then grab the first part of the array but that's not the most elegant solution.

For example

$string = "/gallery/image?a=b";
$string = imaginary_function($string,'?');
echo $string; //echoes "/gallery/image"

Does anyone know of a good cheat sheet for php string manipulation functions? Thanks

like image 864
andrew Avatar asked Dec 02 '09 06:12

andrew


2 Answers

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.

like image 169
jheddings Avatar answered Oct 14 '22 23:10

jheddings


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
like image 20
Ja͢ck Avatar answered Oct 14 '22 23:10

Ja͢ck