Pregunta

No soy muy bueno con las expresiones ... He mirado en algunos tutoriales en línea, pero todavía no estoy consiguiendo. Básicamente, estoy tratando de volver TRUE si una cadena tiene el formato siguiente:

4 dígitos + Espacio + 2 dígitos y convertirlo a una fecha.

Por lo tanto, la cadena se verá así: 2010 02, y yo estoy tratando de February, 2010 salida.

Estoy tratando de utilizar preg_match, pero me siguen dando

  

{no es un modificador ...

editar

Por las 2 primeras respuestas, me cambiaron, pero estoy recibiendo un error grave en el primer y el mismo error modificador desconocido en el segundo:

if(preg_match('/([0-9{4}]) ([0-9]{2})/iU',$path_part)) {
    $path_title = date("F, Y",strtotime(str_replace(" ","-", $path_title)));
}

Además, acaba de intentar la versión más en profundidad en la primera respuesta, y mientras que el error desaparece, no cambia la salida ...

$path_part = '2010 02';
if(preg_match('/^(\d{4}) (\d{2})$/',$path_part,$matches)) {
   $path_title = $mon[(int)$matches[2]] . " " . $matches[1]; // prints Feb 2010
}
¿Fue útil?

Solución

Estoy intentando devolver TRUE si una cadena tiene el formato siguiente manera: 4 dígitos + espacio + 2 dígitos

return preg_match(/^\d{4} \d{2}$/,$input);

Para convertir hasta la fecha se puede intentar algo como:

$mon = array('','Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec');
$date_str = "2010 02";

if(preg_match('/^(\d{4}) (\d{2})$/',$date_str,$matches))
{
        print $mon[(int)$matches[2]] . " " . $matches[1]; // prints Feb 2010
}

Otros consejos

Prueba con esto ...

preg_match('/([0-9{4}]) ([0-9]{2})/iU', $input);

Sin tener ningún detalle en cuanto a su código actual, el siguiente debería funcionar:

<?php

$str = '2010 02';

$months = array('January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December');

if(preg_match('/([0-9]{4}) ([0-9]{2})/', $str, $match) == 1){
    $year = $match[1];
    $month = (int) $match[2];
    echo $months[$month - 1] . ', ' . $year;
}else{
    //Error...
}

?>
$in = "2010 02";
if(preg_match('/([0-9]{4}) ([0-9]{2})/i', $in, $matches)) {
        echo date("F Y", strtotime($matches[2] . "/1/" . $matches[1]));
}

También puede utilizar T-Regx biblioteca

$string = '2010 02';

pattern('\d{4} \d{2}')->match($string)->first(function (Match $match) 
{
    $year = $match->group(1);
    $month = $match->group(2);
});
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top