Jump to content

Check how many times a word is written


aQ

Recommended Posts

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

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

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.