aQ Posted July 19, 2007 Share Posted July 19, 2007 Hey! I am trying to check how many times a word is written in a variable. Lets say I have a story, and want to know how many times "walked" is written. I guess I will need a loop of some kind, but I'm not sure. Thank you. Quote Link to comment Share on other sites More sharing options...
GingerRobot Posted July 19, 2007 Share Posted July 19, 2007 The substr_count() function should be what you need. Quote Link to comment Share on other sites More sharing options...
aQ Posted July 19, 2007 Author Share Posted July 19, 2007 Thanks! I have one more question: How can I replace these words with growing numbers, so that the first "walked" is replaced with 1, the second one 2, 3, 4 and so on? Quote Link to comment Share on other sites More sharing options...
chigley Posted July 19, 2007 Share Posted July 19, 2007 I doubt you could replace them with the substr_count() function, give this a go: <?php $story = "My friend once went walking upon a pier, I love walking too!"; $search = "walking"; $words = explode(" ", $story); $storyout = ""; $count = 1; foreach($words as $word) { if($word == "walking") { $storyout .= "{$count} "; $count++; } else { $storyout .= "{$word} "; } } $storyout = substr($storyout, 0, (strlen($storyout) - 1); ?> Case sensitive, and won't work if the word is next to a comma or anything like that! At least it's a starting point Quote Link to comment Share on other sites More sharing options...
jitesh Posted July 19, 2007 Share Posted July 19, 2007 substr_count (PHP 4, PHP 5) substr_count -- Count the number of substring occurrences Quote Link to comment Share on other sites More sharing options...
aQ Posted July 19, 2007 Author Share Posted July 19, 2007 There is a parse error on the last line. Seems like a ( or ) is missing? Quote Link to comment Share on other sites More sharing options...
chigley Posted July 19, 2007 Share Posted July 19, 2007 $storyout = substr($storyout, 0, (strlen($storyout) - 1)); My bad Quote Link to comment Share on other sites More sharing options...
SammyP Posted July 19, 2007 Share Posted July 19, 2007 Try this: echo ReplaceStringWithNumbers("My friend once went walking upon a pier, I love walking too!", "walking"); function ReplaceStringWithNumbers($haystack, $needle, $count = 0) { if (($pos = strpos($haystack, $needle)) !== false) return substr($haystack, 0, $pos).($count+1).ReplaceStringWithNumbers(substr($haystack, $pos+strlen($needle)), $needle, $count+1); else return $haystack; } Quote Link to comment Share on other sites More sharing options...
aQ Posted July 19, 2007 Author Share Posted July 19, 2007 I used sammyP's method. Great function! Thank you all. Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.