How to remove anything in a string after “-”?

后端 未结 7 954
迷失自我
迷失自我 2020-12-23 15:05

This is the example of my string.

$x = \"John Chio - Guy\";
$y = \"Kelly Chua - Woman\";

I need the pattern for the reg replace.

         


        
7条回答
  •  不知归路
    2020-12-23 15:36

    No need for regex. You can use explode:

    $str = array_shift(explode('-', $str));
    

    or substr and strpos:

    $str = substr($str, 0, strpos($str, '-'));
    

    Maybe in combination with trim to remove leading and trailing whitespaces.

    Update: As @Mark points out this will fail if the part you want to get contains a -. It all depends on your possible input.

    So assuming you want to remove everything after the last dash, you can use strrpos, which finds the last occurrence of a substring:

    $str = substr($str, 0, strrpos($str, '-'));
    

    So you see, there is no regular expression needed ;)

提交回复
热议问题