WebNovice
WebNovice

Reputation: 2220

PHP extract text separated by period

I have texts in the format:

123232.23

43438282.00

I want to extract and store them into two variables $dollar and $cent.

Desired result will be as follows for the first text:

$dollar = '123232'

$cent = '23'

How can I achieve that using regex in PHP.

Upvotes: 0

Views: 3125

Answers (3)

Mob
Mob

Reputation: 11098

You can use a simple explode function for it if you have only single individual strings, but if you have multiple figures in a text file and you want to extract them, you do something like this below.

For the first delimiter I used a newline character `\n. You can change it to what fits you.

$s = <<<ABC
123232.23
43438282.00
3333.66
ABC;

$arr = explode("\n", $s);
print_r($arr);
$exarr = array();
foreach($arr as $arv){
    $exarr[] = explode(".", $arv);
}

print_r($exarr);

This would parse each or the figures and output something similar to this below :

Array
(
    [0] => 123232.23
    [1] => 43438282.00 
    [2] => 3333.66
)
Array
(
    [0] => Array
        (
            [0] => 123232
            [1] => 23
        )

    [1] => Array
        (
            [0] => 43438282
            [1] => 00 
        )

    [2] => Array
        (
            [0] => 3333
            [1] => 66
        )

)

Upvotes: 1

ioseb
ioseb

Reputation: 16951

Here is the regular expression for this:

$regex = '~^(?P<dollar>\d+)\.(?P<cent>\d+)$~';

if (preg_match($regex, $number, $matches)) {
  //$matches['dollar']
  //$matches['cent']
}

Upvotes: 3

Shakti Singh
Shakti Singh

Reputation: 86366

why not just use explode with list

list($dollar, $cent) = explode('.', $text);

Upvotes: 9

Related Questions