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

前端 未结 5 1438
予麋鹿
予麋鹿 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:01

    How about this:

    $string = "The quick brown fox jumped over the etc etc.";
    
    $splitter = " ";
    
    $pieces = explode($splitter, $string);
    
    echo $pieces[0];
    
    0 讨论(0)
  • 2020-11-28 10:05

    strstr() Find the first occurrence of a string. Returns part of haystack string starting from and including the first occurrence of needle to the end of haystack.

    Third param: If TRUE, strstr() returns the part of the haystack before the first occurrence of the needle (excluding the needle).

    $haystack  = 'The quick brown foxed jumped over the etc etc.';
    $needle    = ' ';
    echo strstr($haystack, $needle, true);
    

    Prints The.

    0 讨论(0)
  • 2020-11-28 10:20

    for googlers: strtok is better for that

    echo strtok("The quick brown fox",  ' ');
    
    0 讨论(0)
  • 2020-11-28 10:23

    You could do this:

    $string = 'The quick brown fox jumped over the lazy dog';
    $substring = substr($string, 0, strpos($string, ' '));
    

    But I like this better:

    list($firstWord) = explode(' ', $string);
    
    0 讨论(0)
  • 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;
    
    0 讨论(0)
提交回复
热议问题