Home > Blockchain >  How to alter the snippet below to fetch the second value in between the delimeters?
How to alter the snippet below to fetch the second value in between the delimeters?

Time:12-16

How to alter the snippet below to fetch the first and second value in between the delimeters?

Output Example: First value: 9100450 and second value: HHkk based on the searchfor value: 12348888

$input = '0123456|BHKAHHHHkjkjkjkjk|12345678|JuiKKK121255
    9100450|HHkk|12348888|JuiKKK10000000021sdadad255';
$searchfor = '12348888';
$regexp = "/(?<=" . $searchfor . "\\|)\\w /m";
$result = preg_match_all($regexp, $input, $matches);
print_r($matches);

CodePudding user response:

You can use

$regexp = "/^([^|] )\|([^|] )\|" . $searchfor . "\|/m";

See the PHP demo and the regex demo. Details:

  • ^ - (here, due to m) start of a line
  • ([^|] ) - Group 1: any one or more chars other than a | char
  • \| - a | char
  • ([^|] ) - Group 2: any one or more chars other than a | char
  • \| - a | char
  • 12348888 - some hard-coded value
  • \| - a | char.

If your $searchfor value can contain special chars, replace $searchfor with preg_quote($searchfor, '/') in the code.

See a PHP demo:

$input = '0123456|BHKAHHHHkjkjkjkjk|12345678|JuiKKK121255
9100450|HHkk|12348888|JuiKKK10000000021sdadad255';
$searchfor = '12348888';
$regexp = "/^([^|] )\|([^|] )\|" . $searchfor . "\|/m";
if (preg_match($regexp, $input, $match)) {
    $val1 = $match[1];
    $val2 = $match[2];
    echo "$val1\n$val2";
}
  • Related