Domanda

  

Duplica: esplodere su ogni altra parola

$string = "This is my test case for an example."

Se lo faccio esplodere sulla base di ' ' ottengo un

Array('This','is','my','test','case','for','an','example.');

Quello che voglio è un esplodere per ogni altro spazio.

sto cercando il seguente output:

Array( 

[0] => Array ( 

[0] => This is
[1] => is my
[2] => my test
[3] => test case 
[4] => case for 
[5] => for example. 

)

Quindi, in pratica ogni 2 frasi formulate viene riprodotto.

Qualcuno sa una soluzione ????

È stato utile?

Soluzione

questo fornirà l'uscita che stai cercando

$string = "This is my test case for an example.";
$tmp = explode(' ', $string);
$result = array();
//assuming $string contains more than one word
for ($i = 0; $i < count($tmp) - 1; ++$i) {
    $result[$i] = $tmp[$i].' '.$tmp[$i + 1];
}
print_r($result);

Avvolto in una funzione:

function splitWords($text, $cnt = 2) 
{
    $words = explode(' ', $text);

    $result = array();

    $icnt = count($words) - ($cnt-1);

    for ($i = 0; $i < $icnt; $i++)
    {
        $str = '';

        for ($o = 0; $o < $cnt; $o++)
        {
            $str .= $words[$i + $o] . ' ';
        }

        array_push($result, trim($str));
    }

    return $result;
}

Altri suggerimenti

Un'alternativa, facendo uso di puntatori 'caccia', sarebbe questo snippet.

$arr = explode( " ", "This is an example" );
$result = array();

$previous = $arr[0];
array_shift( $arr );
foreach( $arr as $current ) {
    $result[]=$previous." ".$current;
    $previous = $current;
}

echo implode( "\n", $result );

E 'sempre divertente, non ha bisogno di indici e conta ma lasciare tutte queste cose rappresentazione interna al metodo foreach (o array_map, o simili).

Una breve soluzione senza loop (e un numero di parole variabile):

    function splitStrByWords($sentence, $wordCount=2) {
        $words = array_chunk(explode(' ', $sentence), $wordCount);
        return array_map('implode', $words, array_fill(0, sizeof($words), ' '));
    }

Due opzioni rapide vengono in mente: esplode di ogni parola e rimontare a due a due, usare un'espressione regolare per dividere la stringa, invece di esplodere ()

.
$arr = explode($string);
$arr2 = array();
for ( $i=0; $i<size($arr)-1; $i+=2 ) {
    $arr2[] = $arr[i].' '.$arr[i+1];
}
if ( size($arr)%2==1 ) {
    $arr2[] = $arr[size($arr)-1];
}

$ arr2 è la soluzione.

  $content="This is my test case for an example";
  $tmp=explode(" ",$content);
  $text = array();
  $b=0;
  for ($i = 0; $i < count($tmp)/2; $i++) {
      $text[$i] = $tmp[$b].' '.$tmp[$b + 1];
      $b++;
  $b++;
  }
  print_r($text);
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top