One way to find the longest word in a string in PHP is to convert the string into an array of words, loop through each word to determine its length, and keep track of the longest word found so far.
Here's an example implementation:
main.php351 chars13 lines
In this code, we first use the explode()
function to convert the string into an array of words, splitting it at every space character. We then set an initial value of an empty string for the variable $longest_word
.
Next, we loop through each word in the array using a foreach
loop. For each word, we check if its length is greater than the length of the current $longest_word
. If it is, we update the value of $longest_word
to be the current word.
Once the loop has finished, we output the value of $longest_word
to display the longest word in the original string.
gistlibby LogSnag