How can I split a string at the first occurrence of “-” (minus sign) into two $vars with PHP?

后端 未结 4 1831
逝去的感伤
逝去的感伤 2020-12-14 05:25

How can I split a string at the first occurrence of - (minus sign) into two $vars with PHP?

I have found how to split on every \"-\" but, not only on the first occur

相关标签:
4条回答
  • 2020-12-14 05:48
    $array = explode('-', 'some-string', 2);
    

    Then you could do $var1=$array[0] and $var2=$array[1].

    0 讨论(0)
  • 2020-12-14 05:51

    You can use strtok function:

    $first = strtok($string, '-');
    
    0 讨论(0)
  • 2020-12-14 05:52

    It's very simple, using an extra paramater to explode that many people don't realize is there:

    list($before, $after) = explode('-', $source, 2);

    0 讨论(0)
  • 2020-12-14 06:13

    Here is what you need: using list() with explode():

    list($var1, $var2) = explode(' - ', 'this - is - line - of whatever - is - relevant', 2);
    

    Note the spaces around the "-" (minus sign)

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