Dj Daihatsu Dj Daihatsu - 4 months ago 7
PHP Question

PHP: How can I find all possible sequences of any length within a string?

I want to take a user input (string) and convert it into a list of word combinations (array) of all possible lengths, but only keep the combinations which are in sequence.

So the array listed in the PHP below would eventually read:

$newArray = ["this","string","will","be","chopped","up","this string","will be","be chopped","chopped up","this string will","string will be","be chopped up"];


My code (not working) is as follows:

PHP

$str = "This string will be chopped up.";
$str = strtolower($str);
$strSafe = preg_replace("/[^0-9a-z\s-_]/i","",$str);
$array = explode(" ", $strSafe);
$newArray = [];
$newArrayEntry = [];

for($counter=0; $counter < COUNT($oneword); $counter++) {

// List single words - as in array $oneword.
echo "One word: ";
echo $oneword[$counter];
echo "<br />";

$counterTwo = $counter+1;

if($counterTwo <= COUNT($oneword)) {
$newArrayEntry[COUNT($newArrayEntry)] = $oneword[$counter];
print "Adding counter One to newArray Entry: ".$oneword[$counter]."<br />";
for($counterThree=($counter+1); $counterThree < $counterTwo; $counterThree++) {
$newArrayEntry[COUNT($newArrayEntry)] = $oneword[$counterThree];

if($counterThree - $counterTwo == 1) {
$newArrayEntry[COUNT($newArrayEntry)] = $oneword[$counterTwo];
print "Adding counter Two to newArrayEntry: ".$oneword[$counterTwo]."<br />";
}
}
$newArrayString = join(' ', $newArrayEntry);
$newArray[COUNT($newArray)] = $newArrayString;
}
}

Answer

You could use this code:

$str = "This string will be chopped up.";
$str = strtolower($str);
$strSafe = preg_replace("/[^0-9a-z\s-_]/i","",$str);
$array = explode(" ", $strSafe);
$newArray = [];

for ($len = 1; $len <= count($array); $len++) {
    for($start = 0; $start+$len <= count($array); $start++) {
        $newArray[] = implode(" ", array_slice($array, $start, $len));
    }
}   


var_export($newArray);  

Output:

array (
  0 => 'this',
  1 => 'string',
  2 => 'will',
  3 => 'be',
  4 => 'chopped',
  5 => 'up',
  6 => 'this string',
  7 => 'string will',
  8 => 'will be',
  9 => 'be chopped',
  10 => 'chopped up',
  11 => 'this string will',
  12 => 'string will be',
  13 => 'will be chopped',
  14 => 'be chopped up',
  15 => 'this string will be',
  16 => 'string will be chopped',
  17 => 'will be chopped up',
  18 => 'this string will be chopped',
  19 => 'string will be chopped up',
  20 => 'this string will be chopped up',
)
Comments