andrew
andrew

Reputation: 5176

Php trim string at a particular character

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

Upvotes: 13

Views: 38104

Answers (7)

Rob
Rob

Reputation: 8185

You could use explode:

$string = "/gallery/image?a=b";
list($url,$querystring) = explode('?', $string, 2);

Upvotes: 21

Ja͢ck
Ja͢ck

Reputation: 173562

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

Upvotes: 2

jheddings
jheddings

Reputation: 27563

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.

Upvotes: 25

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.

Upvotes: 0

Dominic Rodger
Dominic Rodger

Reputation: 99761

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.

Upvotes: 2

Doug Neiner
Doug Neiner

Reputation: 66191

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
}

Upvotes: 7

Gumbo
Gumbo

Reputation: 655239

Try strtok:

$token = strtok($str, '?');

Note that the second parameter is a list of separators and not a separator string.

Upvotes: 10

Related Questions