1

I was in need of a method to count the number of words (not characters) within PHP, and start a <SPAN> tag within HTML to wrap around the remaining words after the specified number.

I looked into functions such as wordwrap and str_word_count, but those didn't seem to help. I went ahead and modified the code found here: http://php.timesoft.cc/manual/en/function.str-word-count.php#55818

Everything seems to work great, however I wanted to post here as this code is from 2005 and maybe there is a more modern / efficient way of handling what I'm trying to achieve?

<?php
$string = "One two three four five six seven eight nine ten.";

// the first number words to extract
$n = 3;

// extract the words
$words = explode(" ", $string);

// chop the words array down to the first n elements
$first = array_slice($words, 0, $n);

// chop the words array down to the retmaining elements
$last = array_slice($words, $n);

// glue the 3 elements back into a spaced sentence
$firstString = implode(" ", $first);

// glue the remaining elements back into a spaced sentence
$lastString = implode(" ", $last);


// display it
echo $firstString;
echo '<span style="font-weight:bold;"> '.$lastString.'</span>';
?>
Joe
  • 5,955
  • 2
  • 29
  • 42
  • I think there is no other way to find solution. use built-in functions like this, or you need to achieve this using iterate loops like `for`, `while` – Ranjith Jun 13 '14 at 07:43

4 Answers4

3

You could use preg_split() with a regex instead. This is the modified version of this answer with an improved regex that uses a positive lookbehind:

function get_snippet($str, $wordCount) {
    $arr = preg_split(
        '/(?<=\w)\b/', 
        $str, 
        $wordCount*2+1, 
        PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY
    );

    $first = implode('', array_slice($arr, 0, $wordCount));
    $last = implode('', array_slice($arr, $wordCount));

    return $first.'<span style="font-weight:bold;">'.$last.'</span>';
}

Usage:

$string = "One two three four five six seven eight nine ten.";
echo get_snippet($string, 3);

Output:

One two three four five six seven eight nine ten.

Demo

Community
  • 1
  • 1
Amal Murali
  • 75,622
  • 18
  • 128
  • 150
1

Lets more even simple . Try this

<?php

    $string = "One two three four five six seven eight nine ten.";

    // the first number words to extract
    $n = 2;

    // extract the words
    $words = explode(" ", $string);

    for($i=0; $i<=($n-1); $i++) {
      $firstString[] = $words[$i];  // This will return one, two
    }

    for($i =$n; $i<count($words); $i++) {
      $firstString[] = $words[$i];  // This will return three four five six seven eight nine ten
    }

    print_r($firstString);
    print_r($firstString);
?>

Demo here

Ranjith
  • 2,779
  • 3
  • 22
  • 41
0

I borrowed the code from here:

https://stackoverflow.com/a/18589825/1578471

/**
 * Find the position of the Xth occurrence of a substring in a string
 * @param $haystack
 * @param $needle
 * @param $number integer > 0
 * @return int
 */
function strposX($haystack, $needle, $number){
    if($number == '1'){
        return strpos($haystack, $needle);
    }elseif($number > '1'){
        return strpos($haystack, $needle, strposX($haystack, $needle, $number - 1) + strlen($needle));
    }else{
        return error_log('Error: Value for parameter $number is out of range');
    }
}

$string = "One two three four five six seven eight nine ten.";

$afterThreeWords = strposX($string, " ", 3);

echo substr($string, 0, $afterThreeWords); // first three words
Community
  • 1
  • 1
Muqito
  • 1,369
  • 3
  • 13
  • 27
0

This looks good to me, here's another way that you might check against this for efficiency? I have no idea which is quicker. My guess is yours is quicker for longer strings

$string = "This is some reasonably lengthed string";
$n = 3;
$pos = 0
for( $i = 0; $i< $n; $i++ ){
    $pos = strpos($string, ' ', $pos + 1);
    if( !$pos ){
        break;
    }
}
if( $pos ){
    $firstString = substr($string, 0, $pos);
    $lastString = substr($string, $pos + 1);
}else{
    $firstString = $string;
    $lastString = null;
}
Nathan Edwards
  • 311
  • 1
  • 3
  • 17