Home > Net >  How to output the second value in the string between the two delimiters using regex?
How to output the second value in the string between the two delimiters using regex?

Time:12-15

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;
         
    }

CodePudding user response:

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 :(');

?>

CodePudding user response:

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
        )

)*/
  • Related