Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

174
Vistas
How to output the second value in the string between the two delimiters using regex?

I am fetching data from a text file. How can I fetch the value in between the two delimiters i.e. | based on the match. The first 7 characters are part of the id.

Input Example:

    0123456|BHKAHHHHkk|12345678|JuiKKK121255
    9100450|HHkk|12348888|JuiKKK10000000021sdadad255

Desired Output: BHKAHHHHkk based on the searchfor value = 0123456

My Script:

$file = 'file.txt';


// the following line prevents the browser from parsing this as HTML.
header('Content-Type: text/plain');

// get the file contents, assuming the file to be readable (and exist)
$contents = file_get_contents($file);
// escape special characters in the query
$txt = explode("\n",$contents);

$counter = 0;
foreach($txt as $key => $line){
    $subbedString = substr($line,2,6);

   // $searchfor = '0123456';
    //echo strpos($subbedString,$searchfor); 
    if(strpos($subbedString,$searchfor) === 0){
        $matches[$key] = $searchfor;
        
          echo  "<p>" . $matches[$key] . "</p>";
          
                  $counter += 1;
                  if($counter==10) break;
         
    }
over 4 years ago · Santiago Trujillo
2 Respuestas
Responde la pregunta

0

preg_match function can be used for this purpose and it makes your code very simple and readable.

Each row of data starts with \n or start of the content, so \n|^ for the beginning of the pattern is used; Also ?: is used to prevent listing this part in the $matchs variable.

Each row of data ends with \n or end of content, so \n|$ for the end of the pattern is used; \r may appear or not so (?:\r?\n|$) used at the end.

$searchfor variable can be directly in the pattern.

\|([^\n]+) searchs for delimiters and rest of line data.

In the end, the second parameter of the data (which you looking for) can be accessed in the $matchs[1] variable and the rest of the data in the $matchs[2] variable.

<?php

$contents = '0123456|BHKAHHHHkk|12345678|JuiKKK121255
9100450|HHkk|12348888|JuiKKK10000000021sdadad255';

$searchfor = '9100450';

if(preg_match('/(?:\n|^)' . $searchfor .  '\|([^|]+)(.*?)(?:\r?\n|$)/is', $contents, $matchs))
{
    $second_value = $matchs[1];
    $reset_values = $matchs[2];
    echo "Result for searching <b>$searchfor</b> is <b>$second_value</b> and reset of data is <b>$reset_values</b>";
}
else echo('Not Found :(');

?>
over 4 years ago · Santiago Trujillo Denunciar

0

Using regular expressions works for me:

$input = '0123456|BHKAHHHHkk|12345678|JuiKKK121255
9100450|HHkk|12348888|JuiKKK10000000021sdadad255';

$searchfor = '12348888';

$regexp = "/(?<=" . $searchfor . "\\|)\\w+/m";

$result = preg_match_all($regexp, $input, $matches);

print_r($matches);

Output:

/*Array
(
    [0] => Array
        (
            [0] => JuiKKK10000000021sdadad255
        )

)*/
over 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda