Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

175
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda