Search code examples
phpregextext-extraction

Get string before hyphen


So I have a delimited string and I need to get the substring before the delimiter, let's take an example:

This string - DeleteMe please and some other text

So I want to find DDeleteMe please and some other text and remove it, because all I need is This string.


Solution

  • So everything before the dash - or how does DeleteMe please and some other text qualifies to be deleted?

    If so, you need no regex, you can do it with substr and strpos:

    $string = "This string - DeleteMe please and some other text";
    $string = trim(substr($string, 0, strpos($string, '-')));
    

    You could also use explode():

    $parts = explode('-', $string);
    $string = trim($parts[0]);