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
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.
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.
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.
You can use the PHP ltrim() function to remove the first character from the given string in PHP.
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);
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"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With