newcomer
newcomer

Reputation: 465

Find a Word after a particular word

I am not so expert in the regular expression. I have created a function to find out a particular word after a first match word from an array. the code is

$searchkey1 = array('NUMBER', 'REF', 'TRANSACTION NUMBER');
$searchkey2 = array('CURRENT BALANCE RS.', 'NEW BALANCE IS');
$smsdata = "TRANSACTION NUMBER NER13082010132400255 TO RECHARGE 198 INR TO 9999999999 IS SUCCESSFUL. YOUR NEW BALANCE IS 8183.79 INR.";

function get_details($searchkey, $smsdata)
{
    foreach ($searchkey as $key) {
        $result = preg_match_all("/(?<=(" . $key . "))(\s\w*)/", $smsdata, $networkID);
        $myanswer = @$networkID[0][0];
    }
    return $myanswer;
}

echo get_details($searchkey1, $smsdata);
echo "<BR>";
echo get_details($searchkey2, $smsdata);

I am using this function to find out other words also. and it is working find for any other words except the decimal value. Here in my example code the return value is 11192 but i would like to get with decimal as 11192.75

Please rectify my error.

$result=preg_match_all("/(?<=(".$key."))(\s\w*)/",$smsdata,$networkID);

give the result NER13082010132400255 and 8183 //here the demical is ignore.

$result=preg_match_all("/(?<=(".$key."))\s*(\d*\.?\d*)/",$smsdata,$networkID);

give the result "blank" and 8183.79 // here the first results is blank

My desire result is NER13082010132400255 and 8183.79

Upvotes: 0

Views: 127

Answers (2)

jaeheung
jaeheung

Reputation: 1208

The OP's regexp captures the leading space too. @DevZer0's regexp captures the trailing dot too. This gives the balance only:

$result=preg_match_all("/(?<=(".$key."))\s*(\d*\.?\d*)/",$smsdata,$networkID);

Upvotes: 1

DevZer0
DevZer0

Reputation: 13525

i don't believe \w covers period. use a mixture of \d and \.

$result=preg_match_all("/(?<=(".$key."))(\s[\d\.]+)/",$smsdata,$networkID);

Upvotes: 2

Related Questions