Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to remove first word from a php string

Tags:

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

like image 482
Monkeyalan Avatar asked Jul 25 '11 22:07

Monkeyalan


People also ask

How do I remove a word from a string in PHP?

Answer: Use the PHP str_replace() function You can use the PHP str_replace() function to replace all the occurrences of a word within a string.

How do I remove the first word from a string?

To remove the first word from a string, call the indexOf() method to get the index of the first space in the string. Then use the substring() method to get a portion of the string, with the first word removed.

How can I get the first word of a string in PHP?

echo "The first word of string is: " . $arr [0]; ?> Method 3: Using strstr() Function: The strstr() function is used to search the first occurrence of a string inside another string.

How do I remove the first character of a string in PHP?

You can use the PHP ltrim() function to remove the first character from the given string in PHP.


2 Answers

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); 
like image 175
amosrivera Avatar answered Nov 01 '22 12:11

amosrivera


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" 
like image 42
Alex Avatar answered Nov 01 '22 14:11

Alex