Return the portion of a string before the first occurrence of a character in php

前端 未结 5 1470
予麋鹿
予麋鹿 2020-11-28 09:41

In PHP, what is the simplest way to return the portion of a string before the first occurrence of a specific character?

For example, if I have a string...

\"

5条回答
  •  时光说笑
    2020-11-28 10:23

    To sum up there're 4 ways

    strstr($str,' ',true);
    strtok($str,' ');
    explode(' ', $str)[0];  //slowest
    substr($str, 0, strpos($str, ' '));
    

    The difference is that if no delimiter found:

    strstr returns false

    strtok explode returns whole string

    substr returns empty string

    if unexpected troubles with multibyte appear then this example

    $str = mb_strstr($str, 'и', true) ?: $str;
    

提交回复
热议问题