Home > Net >  How to fetch second value in string based on the matched value before the delimeter "|"?
How to fetch second value in string based on the matched value before the delimeter "|"?

Time:12-17

How to fetch second value in string based on the matched value before the delimeter "|"?

Desired Output:

12348888
113336669998888

Based on the searchfor value: 1254698

<?php

        $contents = '12345|BHKAHHHHkk
1254698|12348888
12345|BHKNe22223366
1254698|113336669998888
012250000|22154545488888';

    $searchfor = '1254698';
    
    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:

You can use

<?php

$contents = '12345|BHKAHHHHkk
1254698|12348888
12345|BHKNe22223366
1254698|113336669998888
012250000|22154545488888';

$searchfor = '1254698';
    
if(preg_match_all('/^' . $searchfor .  '\|([^|\r\n] )/m', $contents, $matchs))
{
    print_r($matchs[1]);
} else {
    echo('Not Found :(');
}

See the enter image description here

link to get the code generated for you.

CodePudding user response:

Don't use a regexp, use a loop and split each line at | characters.

$lines = file($input_file, FILE_IGNORE_NEW_LINE)
$found = false;
foreach ($lines as $line) {
    [$first_value, $second_value, $reset_values] = explode('|', $line, 3);
    if ($cols[0] == $searchfor) {
        echo "Result for searching <b>$searchfor</b> is <b>$second_value</b> and reset of data is <b>$reset_values</b>";
        $found = true;
    }
}
if (!$found) {
    echo 'Not Found :(';
}
  • Related