You don't have access to this class

Keep learning! Join and start boosting your career

Aprovecha el precio especial y haz tu profesión a prueba de IA

Antes: $249

Currency
$209
Suscríbete

Termina en:

0 Días
10 Hrs
50 Min
42 Seg
Curso de Expresiones Regulares

Curso de Expresiones Regulares

Alberto Alcocer (Beco)

Alberto Alcocer (Beco)

Utilizando PHP en la práctica

24/29
Resources

How to work with soccer match data using PHP?

In the world of programming, sometimes small things make a big difference. Analyzing soccer match data is a challenge in terms of accuracy and efficiency. Here we will explore how to manipulate national team match data using PHP. Focus on cleaning data, understanding regular expressions and controlling intricate data details such as country names with special characters or match results.

What are the first steps to extract specific information?

To start, we determine what data we want to analyze. For example, we want to get all tied matches in the history of national teams. We start by writing a basic PHP script:

<?php// We clear screen and load data fileecho "\033[2J\033[;H"; // Code to clear screen in terminal
// We load data from file$filename = "Results.txt";$file = fopen($filename, "r");
// Initialize flag to make match insensitive to case$flags = "i";
// Set regular expression pattern (Regex)$pattern = '/(\(\d{4})-(\d{2})-(\d{2}),(([\w}s},(.*?)-([\w\s\-]+),(.*?)-(\d+),(\d+),.*?(Friendly|Eliminator|Competition)/';
while (($line = fgets($file)) !== false) { if (preg_match($pattern, $line, $match)) { $localTeam = $match[4]; $visitorTeam = $match[6]; $localScore = $match[8]; $visitorScore = $match[9];
 // We evaluate the match result if ($localScore == $visitorScore) { echo "Tie:  $localTeam vs $visitorTeam $localScore-$visitorScore\n"; } } } }fclose($file);?>

How to fix common data problems?

One of the common challenges in this type of data is dealing with non-standard characters, such as accents or cedillas, in team names. In cases like these, we can adjust our Regex to accept additional characters, which is vital to ensure that all information is considered.

Next, we refine our regular expression to include spaces and hyphens in country names:

$pattern = '/(\d{4})-(\d{2})-(\d{2}),([\w\s\-\']+),(.*?)-([\w\s\-\']+),(.*?)-(\d+),(\d+),.*?(Friendly|Eliminatorio|Competencia)/';

How to generate more useful information?

The idea is not only to extract data, but also to process it to create understandable information at a glance. For example, we can modify the printout to add labels that clearly determine whether the result of the match was a draw or whether a particular team won.

if ($localScore == $visitorScore) { printf("%s, %s vs %s: Tie (%d-%d)\n", $match[1], $localTeam, $visitorTeam, $localScore, $visitorScore);} elseif ($localScore > $visitorScore) { printf("%s, %s vs %s: Local (%d-%d)\", $match[1], $localTeam, $visitorTeam, $localScore, $visitorScore);} else { printf("%s, %s vs %s: Visitor (%d-%d)\", $match[1], $localTeam, $visitorTeam, $localScore, $visitorScore);} }

Why is efficiency important when processing data?

Efficiency must be taken into account when manipulating large volumes of data. Using properly configured regular expressions allows processing large data sets in a short time. Here we calculate the time it takes for our script to run:

$startTime = microtime(true);
// ... data processing ...
 $endTime = microtime(true);$executionTime = $endTime - $startTime;echo "Execution time: " . round($executionTime, 2) . " seconds. "

By measuring the time, we can make comparisons and improve processing algorithms, achieving more effective scripts.

How to handle common errors during execution?

During execution it is common to face errors such as lines not matching the regular expression. These may be due to unexpected characters or missing data. A useful trick is to print only the lines that do not match in order to quickly identify the source of the problem:

while (($line = fgets($file)) !== false) { if (!preg_match($pattern, $line, $match)) { echo "Line no match: $line\n"; } else { // Process the line if it does match } }}

This approach allows us to quickly adjust regular expressions or data pending review. In situations where the result is not as expected, debugging in this way shortens the development cycle.

How does one continue to learn programming?

Programming requires constant learning and adjustment. Practicing extracting, processing and generating data with various languages such as PHP is just the beginning. In every coding session there is a new lesson to learn, always looking to optimize methods and take the next step to other languages like Python. Keep going, knowledge has no limits!

Contributions 31

Questions 4

Sort by:

Want to see more contributions, questions and answers from the community?

Banderas

Las expresiones regulares pueden tener banderas que afectan la búsqueda, éstas deberán de estar hasta el final de la línea.

Listado de Banderas en js:
i
Con este indicador, la búsqueda no distingue entre mayúsculas y minúsculas: no hay diferencia entre A y a
g
Con esta marca, la búsqueda busca todas las coincidencias, sin ella, solo se devuelve la primera coincidencia.
m
Modo multilínea
s
Habilita el modo “dotall”, que permite un punto. para que coincida con el carácter de nueva línea \ n
u
Permite el soporte completo de Unicode. La bandera permite el procesamiento correcto de pares sustitutos.
y
Modo “adhesivo”: búsqueda en la posición exacta del texto

AWK: Forma una parte esencial del lenguaje y por extensión de la herramienta awk de Unix/Linux

C++: Desde su versión C++ 11 es posible utilizar expresiones regulares mediante la biblioteca estándar, usando la cabecera <regex>.

Java: Existen varias bibliotecas hechas para java que permiten el uso de RegEx, y Sun planea dar soporte a estas desde el SDK.

JavaScript: A partir de la versión 1.2 (ie4+, ns4+) JavaScript tiene soporte integrado para expresiones regulares.

Perl: Es el lenguaje que hizo crecer a las expresiones regulares en el ámbito de la programación hasta llegar a lo que son hoy en día.

PCRE: Biblioteca de ExReg para C, C++ y otros lenguajes que puedan utilizar bibliotecas dll (Visual Basic 6 por ejemplo).

PHP: Tiene dos tipos diferentes de expresiones regulares disponibles para el programador, aunque la variante POSIX (ereg) va a ser desechada en PHP 6.

Python: Lenguaje de scripting con soporte de expresiones regulares mediante su biblioteca re.

.Net Framework: Provee un conjunto de clases mediante las cuales es posible utilizar expresiones regulares para hacer búsquedas, reemplazar cadenas y validar patrones.

Nunca pierdan la capacidad de expresar bien los datos.

Evitemos la frustración, aceptemos los errores y tengamos presente que a la primera no se va ha entender una regex

Muy buena clase e Interesante dato a tener en cuenta sobre \t que permite avanzar espacios en base al siguiente múltiplo de un número y que el más común es 8, para organizar los datos mejor en la consola.

Regex para hacer match con la totalidad de los datos
'/^(\d{4,4}\-\d\d\-\d\d),([\w\-\.\ ñáéíóúçã&]+),([\w\-\.\ ñáéíóúçã&]+),(\d+),(\d+),.*$/i'
Y programa completo:

<?php

$file = fopen("../Curso de Expresiones Regulares/results.csv", "r");

$match = 0;
$nomatch = 0;

$t = time();

while (!feof($file)) {
    $line = fgets($file);
    #echo $line;
    #'/^2018\-01\-(\d\d),.*$/'
    #2018-01-31,Mexico,Bosnia-Herzegovina,1,0,Friendly,San Antonio,USA,TRUE
    if (preg_match('/^(\d{4,4}\-\d\d\-\d\d),([\w\-\.\ ñáéíóúçã&]+),([\w\-\.\ ñáéíóúçã&]+),(\d+),(\d+),.*$/i', $line, $m)) {
        #print_r($m); #imprime el arreglo
        if ($m[4] == $m[5]) {
            echo "empate: " ;
        } elseif ($m[4] > $m[5]) {
            echo "local:   " ;
        } else {
            echo "visitante: ";
        }
        printf("\t%s, %s [%d - %d]\n", $m[2], $m[3], $m[4], $m[5]);
        $match++;
    } else {
        $nomatch++;
        echo $line;
    }
}

fclose($file);

printf("\n\nMatch %d\n No match %d\n", $match, $nomatch);

printf("Tiempo: %d segs\n", time() - $t);

la bandera i es case insensitive y va después del ultimo slash
para debugear se puede imprimir los no matches y verificar el por que no hay coincidencias

<?php
$file = fopen("../files/results.csv","r");
$match   = 0;
$nomatch = 0;
$t = time();
while(!feof($file)) {
    $line = fgets($file);
    if(preg_match('/^(\d{4}\-\d\d\-\d\d),(.+),(.+),(\d+),(\d+),.*$/i', $line, $m)) {
        if ($m[4] == $m[5]) {
            printf("empate: ");
        } elseif ($m[4] > $m[5]) {
            echo "local:  ";
        } else {
            echo "visitante: ";
        }
        printf("\t%s, %s [%d-%d]\n", $m[2], $m[3], $m[4], $m[5]);
        $match++;
    } else {
        $nomatch++;
    }
}
fclose($file);
printf("\n\nmatch: %d\nnomatch: %d\n", $match, $nomatch);
printf("tiempo: %d\n", time() - $t);

Tiempo = 1s también.

solo un aportecito:
de hecho en la presentación, tal vez hubiese sido aun mejor poner el resultado del partido en medio.

entonces quedaria:

India [3-0] Kenya

Increíble, no entiendo nada pero poco a poco se vuelve mas claro jaja

El ejemplo anterior llevado a php

<?php
$t = time();
$file = fopen("../results.csv", "r");
$match = 0;
$nomatch = 0;

while(!feof($file)) {
  $line = fgets($file);
  // 1910-04-10,Netherlands,Belgium,7,0,Friendly,Haarlem,Netherlands,FALSE
  if(preg_match('/^(\d{4,4}\-\d{2,2}\-\d{2,2}).*?,(.*?),(.*?),(\d+),(\d+),.*$/', $line, $m)) {
    if($m[5] > $m[4]) {
      printf("(%s) - %s (%d) - (%d) %s\n",$m[1], $m[2], $m[4], $m[5], $m[3]);
      $match++;
    } else {
      $nomatch++;
    }
  } 
}

fclose($file);
printf("Para los equipos como visitantes se encontraron\n - %d ganados \n - %d perdidos\n", $match, $nomatch);
printf("Tiempo en ejecutar: %d segundos\n", time()-$t);

Solución para encontrar los no match:

preg_match('/^(\d{4}\-\d\d-\d\d),([\w\s\-\.á-ú&]+),([\w\s\-\.á-ú&]+),(\d+),(\d+),.*$/i',$line,$m)

Es increible lo que puede hacer PHP con las expresiones regulares. Mis respetos la verdad para este profe. Saludos

15 segundos :face_palm:

me enreda porque no tiene ordenadas las ideas

La bandera ‘i’ es para case insensitive

\# Conclusión Las expresiones regulares en PHP son extremadamente útiles para validaciones y manipulaciones de texto. Utilizando funciones como `preg\_match`, `preg\_replace`, y `preg\_split`, puedes implementar filtros de datos complejos y realizar búsquedas avanzadas en tus aplicaciones.

como dato curioso, php te permite ponerle alias a los grupos ayuda para organizarse un poco mas.

Buena clase

Es curioso que a fecha 28/06/21 PHP se encuentra en el puesto 8 de popularidad según esta web justo debajo de JS

El código generado, nuevamente se ve bastante bien, aunque no está dentro de mi lista de lenguajes por aprender el PHP, definivamente veo el potencial aquí.

muy buenaa practicaa

5 segundos 😦

Excelente clase.

super poderoso php con regex!! No es el mejor pero es muy popular!

Excelente.

Huy que nota ver esto 😄

gracias

<?php

$file = fopen("./results.csv", “r”);

$match = 0;
$nomatch = 0;

$t = time();

while(!feof($file)) {
$line = fgets($file);
if(preg_match(
’/^(\d{4}-01-\d\d),(.+),(.+),(\d+),(\d+),.*$/i’,
$line,
$m
)
) {
if($m[4] == $m[5]){
printf("Empate: ");
}elseif($m[4] > $m[5]){
echo “local: “;
} else {
echo “visitante”;
}
printf(”\t%s, %s [%d-%d]\n”, $m[2], $m[3], $m[4], $m[5]);
$match++;
} else {
$nomatch++;
}
}
fclose($file);

printf("\n\nmatch: %d\nno match: %d\n", $match, $nomatch);

printf(“tiempo: %d segundos\n”, time() - $t);

Algunas cadenas y expresiones regulares en PHP