2012-01-16 34 views
30

Estoy analizando un texto y calculando el peso según algunas reglas. Todos los personajes tienen el mismo peso. Esto haría que la instrucción switch sea realmente larga. ¿Puedo usar rangos en la sentencia case?sentencia de caso de switch php para manejar rangos

Vi una de las respuestas que abogaban por matrices asociativas.

$weights = array(
[a-z][A-Z] => 10, 
[0-9] => 100, 
['+','-','/','*'] => 250 
); 
//there are more rules which have been left out for the sake of clarity and brevity 
$total_weight = 0; 
foreach ($text as $character) 
{ 
    $total_weight += $weight[$character]; 
} 
echo $weight; 

¿Cuál es la mejor manera de lograr algo como esto? ¿Hay algo similar a la declaración de caso bash en php? Seguramente anotar cada carácter individual en la matriz asociativa o la declaración de cambio no puede ser la solución más elegante o es la única alternativa?

Respuesta

1
$str = 'This is a test 123 + 3'; 

$patterns = array (
    '/[a-zA-Z]/' => 10, 
    '/[0-9]/' => 100, 
    '/[\+\-\/\*]/' => 250 
); 

$weight_total = 0; 
foreach ($patterns as $pattern => $weight) 
{ 
    $weight_total += $weight * preg_match_all ($pattern, $str, $match);; 
} 

echo $weight_total; 

* ACTUALIZACIÓN: con el valor por defecto *

foreach ($patterns as $pattern => $weight) 
{ 
    $match_found = preg_match_all ($pattern, $str, $match); 
    if ($match_found) 
    { 
     $weight_total += $weight * $match_found; 
    } 
    else 
    { 
     $weight_total += 5; // weight by default 
    } 
} 
+0

Muy buen enfoque. – nikhil

+0

En esto, ¿cómo agrego un caso predeterminado? Diga algo que no se encuentra y quiero asignarle un peso fijo. – nikhil

+0

Se encontró algo que no coincide con ninguno de los casos. Ahora no se asigna ningún peso, pero quiero un valor predeterminado distinto de cero. – nikhil

123

Bueno, puede tener rangos en sentencia switch como:

//just an example, though 
$t = "2000"; 
switch (true) { 
    case ($t < "1000"): 
    alert("t is less than 1000"); 
    break 
    case ($t < "1801"): 
    alert("t is less than 1801"); 
    break 
    default: 
    alert("t is greater than 1800") 
} 

//OR 
switch(true) { 
    case in_array($t, range(0,20)): //the range from range of 0-20 
     echo "1"; 
    break; 
    case in_array($t, range(21,40)): //range of 21-40 
     echo "2"; 
    break; 
} 
+0

Gracias, esto es realmente útil. – nikhil

+1

omg genius typecast, ¡tan obvio! gracias –

+0

¡Muy bien !. Pero nadie puede aceptar esto. 40 respuestas 1 voto. Apuesto a que ganas algo de bedge. – vladkras

1

Se puede especificar el rango de caracteres usando expresiones regulares. Esto ahorra escribir una larga lista de casos de cambio. Por ejemplo,

function find_weight($ch, $arr) { 
    foreach ($arr as $pat => $weight) { 
     if (preg_match($pat, $ch)) { 
      return $weight; 
     } 
    } 
    return 0; 
} 

$weights = array(
'/[a-zA-Z]/' => 10, 
'/[0-9]/' => 100, 
'/[+\\-\\/*]/' => 250 
); 
//there are more rules which have been left out for the sake of clarity and brevity 
$total_weight = 0; 
$text = 'a1-'; 
foreach (str_split($text) as $character) 
{ 
    $total_weight += find_weight($character, $weights); 
} 
echo $total_weight; //360 
1

creo que lo haría de una manera sencilla.

switch($t = 100){ 
    case ($t > 99 && $t < 101): 
     doSomething(); 
     break; 
} 
+1

doSomething() siempre se llamará, porque "switch ($ t = 100)" asigna 100 a $ t –

Cuestiones relacionadas