Php trim string at a particular character

前端 未结 7 1343
花落未央
花落未央 2021-01-11 18:32

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

相关标签:
7条回答
  • 2021-01-11 18:58

    You could use explode:

    $string = "/gallery/image?a=b";
    list($url,$querystring) = explode('?', $string, 2);
    
    0 讨论(0)
  • 2021-01-11 19:00

    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
    }
    
    0 讨论(0)
  • 2021-01-11 19:07

    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
    
    0 讨论(0)
  • 2021-01-11 19:09

    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.

    0 讨论(0)
  • 2021-01-11 19:16

    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.

    0 讨论(0)
  • 2021-01-11 19:20
    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.

    0 讨论(0)
提交回复
热议问题