Her kelime üzerinde patlayabilir

7 Cevap php

Ben bir dize var diyelim:

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

Ben 'dayalı patlayabilir eğer' ben bir olsun

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

İstediğim her alanı için patlayabilir olduğunu:

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

Dize kelimelerin bir garip # olabilir, bu yüzden dizideki son öğe iki kelime içeremez.

Herkes bunu nasıl biliyor?

7 Cevap

$matches = array();
preg_match_all('/([A-Za-z0-9\.]+(?: [A-Za-z0-9\.]+)?)/',
       'This is my test case for an example.',$matches);

print_r($matches);

verimleri:

Array
(
  [0] => Array
    (
        [0] => This is
        [1] => my test
        [2] => case for
        [3] => an example.
    )

  [1] => Array
    (
        [0] => This is
        [1] => my test
        [2] => case for
        [3] => an example.
    )

)

update bu cümlenin sonunda tek bir kelime maç için sabit

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

preg_match_all("/[a-zA-Z0-9]+\ [a-zA-Z0-9]+/", $string, $matches);
print_r($matches);

Farklı sınırlayıcı ve sayılar için kullanılabilecek bir işlev.

function explodeEveryNth($delimiter, $string, $n) {
    $arr = explode($delimiter, $string);
    $arr2 = array_chunk($arr, $n);
    $out = array();
    for ($i = 0, $t = count($arr2); $i < $t; $i++) {
    	$out[] = implode($delimiter, $arr2[$i]);
    }
    return $out;
}

Test kod

var_dump(explodeEveryNth(' ', 'This is a test string', 2));

Something You Can Re-Use for Other Scenarios: (her zaman daha iyi IMO).

Muhtemelen en zarif çözüm olsa da, bu diğer PHP temel fonksiyonların genel konsept sözdizimini takip etmez ...

Her durumda ... Bu özyineleme kullanır. Eğer (bu durumda size yolda veya farklı bir proje için bunu yapmak istiyorum) öbek boyutunu belirlemenizi sağlar ki o esnektir. Ben gelip neler yapabileceğini görmek için kişisel bir meydan okuma fazla olarak yaptım.

<?php
function chunk_explode($glue=' ',$pieces='',$size=2,$final=array()) {
    if(!is_string($pieces) && !is_array($pieces)) 
        return false;

    if(is_string($pieces))
        $pieces = explode($glue,$pieces);

    $num_pieces = sizeof($pieces);
    if($num_pieces <= 0) 
       return $final;

    if($num_pieces >= $size) {
        $arr_chunk = array_chunk($pieces, $size);
        array_push($final,implode($glue,$chunk[0]));
        for($i=0;$i<=$size;$i++) { array_shift($pieces); }
        return chunk_explode($glue,$pieces,$size,$final);
    }
    array_push($final,implode($glue,$pieces));
    return $final;
}
$string = "This is my test case for an example.";
chunk_explode(' ',$string,3);

Bu chunk_explode function emerse, bu yüzden benim hatalarımdan öğrenebilirsiniz bana bildirin.

PHP 75 dizi işlevleri vardır, en döngüler için yerine onları kullanmayı deneyelim!

Ben Kyle'ın işlev adını seviyorum. (Ben 5.3 çalıştıran varsayalım ve create_function ile acı çekeceğim.)

 function chunk_explode($string, $chunks = 2, $delim = ' ') {
     $A = explode($delim, $string);
     $A = array_chunk($A, $chunks);
     return array_map(
         create_function('$x',
            'return implode(\'' . $delim . '\',$x);'), $A);
 }

Eh tabii ki bu en iyi çözüm değil, ama benim kendi şekilde sergiyi eğlenceli oldu. Öğrenmek için hala çok ...

function solveThisPuzzle($string) {

$modified_string = preg_replace('(\s)', '+', $string, -1, $count);	
$words = explode('+', $modified_string);

$phrases_arr = array();

for($i = 1; $i < $count+1; $i++) {
	if(($i % 2)) {
		$phrase = $words[$i-1].' '.$words[$i];
		$phrases_arr[] = $phrase;
		unset($phrases_arr[$i]);
	} elseif($i == $count) {
			$phrase = $words[$i];
			$phrases_arr[] = $phrase;
		} else {			
			$phrase = NULL;
		}
}

foreach($phrases_arr as $final_phrase) {
	$solution .= $final_phrase.'<br />';
}

	return $solution;

}

$string = "This is my test case for an example, huzzah!";
echo solveThisPuzzle($string);

This is
my test
case for
an example,
huzzah!

Ben sonuçlarına bakmak ve aslında sonra dizeleri birleştirmek olacaktır.