Remove everything after a character in PHP

后端 未结 8 2989
无人共我
无人共我 2021-02-19 08:09

can any tell how to remove characters after ? in php. I have one string test?=new i need to remove the characters as well as = from that string.

8条回答
  •  刺人心
    刺人心 (楼主)
    2021-02-19 08:43

    You could always try using preg_replace() as well:

    $string = 'test?q=new';
    $result = preg_replace("/\?.+/", "", $string);
    

    If, for some reason, you are wanting to keep the ? in the result... you could also do this:

    $string = 'test?q=new';
    $result = preg_replace("/\?.+/", "?", $string);
    

    (or, you could use a positive look-behind assertion, as @BlueJ774 suggested,) like this:

    $result = preg_replace("/(?<=\?).+/", "", $string);
    

    But ideally, and for future reference, if you are working with a query string, you probably will want to use parse_str at some point, like this:

    $string = 'test?q=new';
    parse_str($string, $output);
    

    Because that will give you an array ($output, in this case,) with which to work with all of the parts of the query string, like this:

    Array
    (
        [test?q] => new
    )
    

    But normally... you would probably just want to be working with the query string by this point... so the output would be more like this:

    Array
    (
        [q] => new
    )
    

提交回复
热议问题