how to remove first word from a php string

…衆ロ難τιáo~ 提交于 2019-12-18 14:17:45

问题


I'd like to remove the first word from a string using PHP. Tried searching but couldn't find an answer that I could make sense of.

eg: "White Tank Top" so it becomes "Tank Top"

Thanks


回答1:


No need for explode or array manipulation, you can use function strstr:

echo strstr("White Tank Top"," ");
//Tank Top

UPDATE: Thanks to @Sid To remove the extra white space you can do:

echo substr(strstr("White Tank Top"," "), 1);



回答2:


You can use the preg_replace function with the regex ^(\w+\s) that will match the first word of a string per se:

$str = "White Tank Top";
$str = preg_replace("/^(\w+\s)/", "", $str);
var_dump($str); // -> string(8) "Tank Top"



回答3:


function remove_word($sentence)
{
 $words=array_shift(explode(' ', $sentence));
 return implode(' ', $words);
}

?




回答4:


$string = 'White Tank Top';

$split = explode(' ', $string);
if (count($split) === 1) {
    // do you still want to drop the first word even if string only contains 1 word?
    // also string might be empty
} else {
    // remove first word
    unset($split[0]);
    print(implode(' ', $split));
}



回答5:


function remove_word($sentence)
{
    $exp = explode(' ', $sentence);
    $removed_words = array_shift($exp);
    if(count($exp)>1){
        $w = implode(' ', $exp);
    }else{
        $w = $exp[0];
    }
    return $w;
}

Try this function i hope it's work for you .




回答6:


If you are not guaranteed to have a space in your string, be careful to choose a technique that won't fail on such cases.

If using explode() be sure to limit the explosions for best efficiency.

Demonstration:

$strings = ["White", "White Tank", "White Tank Top"];
foreach ($strings as $string) {
    echo "\n{$string}:";
    echo "\n-\t" , substr($string, 1 + (strpos($string, ' ') ?: -1));

    $explodeOnce = explode(' ', $string, 2);
    echo "\n-\t" , end($explodeOnce);              

    echo "\n-\t" , substr(strstr($string, " "), 1);

    echo "\n-\t" , ltrim(strstr($string, " "));

    echo "\n-\t" , preg_replace('~^\S+\s~', '', $string);
}

Output:

White:
-   White
-   White
-                       // strstr() returned false
-                       // strstr() returned false  
-   White
White Tank:
-   Tank
-   Tank
-   Tank
-   Tank
-   Tank
White Tank Top:
-   Tank Top
-   Tank Top
-   Tank Top
-   Tank Top
-   Tank Top

My preference is the regex technique because it is stable in all cases above and is a single function call. Note that there is no need for a capture group because the fullstring match is being replaced. ^ matches the start of the string, \S+ matches one or more non-whitespace characters and \s matches one whitespace character.



来源:https://stackoverflow.com/questions/6823133/how-to-remove-first-word-from-a-php-string

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!