2012-02-10 15 views
5

Considere la siguiente secuencia:Separar una cadena en bi-gramos, haciendo caso omiso de ciertas etiquetas

I have had the greatest {A} {B} day yesterday {C} 

Quiero crear una matriz con bi-gramos, haciendo caso omiso de todas las etiquetas (etiquetas son entre {corchetes})

[0] => I-have 
[1] => have-had 
[2] => had-the 
[3] => the-greatest 
[4] => greatest-day 
[5] => day-yesterday 

En PHP, ¿cuál es la mejor manera de hacerlo? ¿Utiliza regex o explosión en "" y luego itera a través de todas las palabras? Estoy teniendo problemas para iniciar de aquí, por lo que cualquier ayuda sería muy apreciada :)

Respuesta

2

Usando explode hace que sea bastante fácil:

$string="I have had the greatest {A} {B} day yesterday {C}"; 

$words=explode(" ",$string); 

$filtered_words=array(); 

foreach($words as $w) 
{ 
    if(!preg_match("/{.*}/",$w)) 
    { 
    array_push($filtered_words,$w); 
    } 
} 


$output=array(); 

foreach(range(0,count($filtered_words)-2) as $i) 
{ 
    array_push($output,$filtered_words[$i] . "-" . $filtered_words[$i+1]); 
} 

var_dump($output); 

la salida es:

array(6) { 
    [0]=> 
    string(6) "I-have" 
    [1]=> 
    string(8) "have-had" 
    [2]=> 
    string(7) "had-the" 
    [3]=> 
    string(12) "the-greatest" 
    [4]=> 
    string(12) "greatest-day" 
    [5]=> 
    string(13) "day-yesterday" 
} 
1

enfoque ligeramente diferente :

$string = '{D} I have had the greatest {A} {B} day yesterday {C}'; 

// explode on spaces 
$arr = explode(' ', $string); 
$bigrams = array(); 

// remove all "labels" with regex (assuming it matches \w) 
$arr = array_values(array_filter($arr, function($s){ 
    return !preg_match("/\{\w\}/", $s); 
})); 

// get the bigrams 
$len = count($arr); 
for ($i = 0; $i <= $len - 2; $i++) { 
    $bigrams[] = $arr[$i] . '-' . $arr[$i+1]; 
} 

print_r($bigrams); 
Cuestiones relacionadas