Jump to content

Check how many times a word is written


aQ

Recommended Posts

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.

Link to comment
Share on other sites

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 ;)

Link to comment
Share on other sites

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;
}

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.