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

后端 未结 7 944
迷失自我
迷失自我 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:27

    Use the strstr function.

    Example:

    $my_string = "This is my best string - You like it?";
    $my_new_string = strstr($my_string, '-', true);
    
    echo($my_new_string);
    
    0 讨论(0)
  • 2020-12-23 15:29

    I hope these patterns will help you =]

    $pattern1='/.+(?=\s-)/'       //This will match the string before the " -";
    $pattern2='/(?<=\s-\s).+/'    //This will match the string after the "- ";
    
    0 讨论(0)
  • 2020-12-23 15:31

    You can also use.

    strstr( "John Chio - Guy", "-", true ) . '-';
    

    The third parameter true tells the function to return everything before first occurrence of the second parameter.

    Source on strstr() from php.net

    0 讨论(0)
  • 2020-12-23 15:32

    Explode or regexp are an overkill, try this:

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

    or the strtok version in one of the answers here.

    0 讨论(0)
  • 2020-12-23 15:35

    To remove everything after the first hyphen you can use this regular expression in your code:

    "/-.*$/"
    

    To remove everything after the last hyphen you can use this regular expression:

    "/-[^-]*$/"
    

    http://ideone.com/gbLA9

    You can also combine this with trimming whitespace from the end of the result:

    "/\s*-[^-]*$/"
    
    0 讨论(0)
  • 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 ;)

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