hello. a part of my code is below. im just wondering if theres a more efficient way of doing this. what it does is take a string and output stars for each word apart from the last three words. so if i input 'How much wood would a wood chuck chuck if a wood chuck could chuck wood' i would get back '** ** could chuck wood'.

<html>
<body>

<?php

if(isset($_POST['sentence']))
{
$sen = $_POST['sentence'];
}


$sen_ar = explode(' ', $sen);


$count = count($sen_ar);


$num = 0;

while($num < $count) 
{

if($num == $count - 3 || $num == $count - 2 || $num == $count - 1)
{
echo $sen_ar[$num] . ' ';
}
else
{
echo '***** ';
}

$num++;
}

?>

</body>
</html>

I dont need to create a function out of it as it only runs once and it does work ok. i just think that i might be going about things in a roundabout way when there could be a built in function for something like this.

thanks

    Here is my version.

    <?php
      $string = 'How much wood would a wood chuck chuck if a wood chuck could chuck wood';
      $out = array();
    
      $arr = explode("\x20", $string); // explode into array on spaces (hex 20)
    
      for($i = 0; $i < count($arr) - 3; $i++){ // loop words - skip last 3
        for($j = 0; $j < strlen($arr[$i]); $j++){ // loop letters and replace
          $out[$i][$j] = '*';
        }
        $out[$i] = implode("", $out[$i]); //implode character array into string
      }
    
      $lastThree = array_slice($arr, count($arr)-3, count($arr)); // get last 3 words
    
      $out = array_merge($out, $lastThree); // merge them together
    
      $out = implode("\x20", $out); // implode into string
    
      echo $out;
    ?>
    *** **** **** ***** * **** ***** ***** ** * **** ***** could chuck wood

      Here is another version, using a function.

      <?php
        function word2star($word){
          if(empty($word))
            return -1;
          for($i = 0; $i < strlen($word); $i++)
            $word[$i] = '*';
      
      return $word;
        }
      
        $string = 'How much wood would a wood chuck chuck if a wood chuck could chuck wood';
      
        $arr = explode("\x20", $string); // explode into array on spaces (hex 20)
      
        $out2 = array();
      
        $arr2 = array_slice($arr, 0, count($arr)-3);
      
        foreach($arr2 as $key => $val){
          $out2[] = word2star($val);
        }
      
        $lastThree = array_slice($arr, count($arr)-3, count($arr)); // get last 3 words
      
        $out2 = array_merge($out2, $lastThree); // merge them together
      
        $out2 = implode("\x20", $out2); // implode into string
      
        echo $out2;
      ?>

        For a slightly shorter version...

        $string = 'How much wood would a wood chuck chuck if a wood chuck could chuck wood'; 
        
        $arr = explode(' ', $string);
        
        for($i=0,$max=count($arr)-3; $i<$max; $i++)
        	$arr[$i] = str_repeat('*', strlen($arr[$i]));
        
        $string = implode(' ', $arr);
        
        echo $string;

          hmm... we could shorten it further with some regex, methinks:

          $string = 'How much wood would a wood chuck chuck if a wood chuck could chuck wood';
          
          if (preg_match('/(.*?)((\s+\w+){3}\s*)$/', $string, $matches)) {
              $string = preg_replace('/[^\s]/', '*', $matches[1]) . $matches[2];
          }
          
          echo $string;

            I wonder which is fastest.

            A little benchmarking shows that bradgrafelman's version is the fastest. That makes sense since it relies on the ordinary string functions, and yet does not do as much string manipulation as your version.

              Do you know how much more load is used when using a regex over Brad's version?

              How are you benchmarking ... running it a bunch of times and showing the times?

                Do you know how much more load is used when using a regex over Brad's version?

                Nope, I did not test that.

                How are you benchmarking ... running it a bunch of times and showing the times?

                Yep, simple empirical testing on a local server.

                Of course, the regex version is more comprehensive as it does not assume that there is exactly one space in between words. It also does not assume no trailing space, but that can easily be fixed in all cases with rtrim(). If these minor details are not going to pose a problem, themanwhowas is probably better off with bradgrafelman's version.

                  Also, while efficiency is a good thing, remember that in most such cases we're talking microseconds or at worst a couple milliseconds difference. While this may be important in extremely large applications and/or extremely high-traffic sites, for the vast majority of the time such differences are trivial compared to the other timing issues involved (e.g. internet transmission time, image downloads, complex database queries, etc.). So while performance of your various PHP functions is of some concern, you generally want desired functionality and code maintainability to drive your choices on how to code something, not how to save a millisecond or two.

                    Write a Reply...