Forum Moderators: coopster

Message Too Old, No Replies

Regular expressions

Problems with preg_split

         

shady

8:56 pm on Jun 15, 2004 (gmt 0)

10+ Year Member



I am trying to extract a numeric from a string! The numeric always appears at the beginning of the string, although it may be preceeded by a currency symbol.

Example strings:
"$123.99 as a deposit"
"123.99 charged to card"

I am trying the following:
$elements=preg_split("/[\s,\£$]+/", $text);

If there is a currency symbol, the result will be contained in $elements[1] and if no currency symbol $elements[0].

To predetermine this I tried using the following:
$elements=preg_split("/[\s,\£$]+/", $text,PREG_SPLIT_NO_EMPTY);

Strangely, this returns the whole string in $elements[0]!

Is this a bug or am I doing something wrong? Is there a better way to achieve this? Is there any way I could cope with the Euro symbol or HTML special characters (£ etc..)

Thanks for your help
Shady

IanKelley

1:46 am on Jun 16, 2004 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



Use this a preg_match like this instead...

preg_match('/^\$?([\d\.]+)',$in,$out);

shady

9:32 am on Jun 16, 2004 (gmt 0)

10+ Year Member



Hi Ian

It doesn't work, but thanks anyway!

Regards
Laurence

vincevincevince

11:00 am on Jun 16, 2004 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



$elements=preg_split("/[\£\$]/", $text);

if I were you

timster

12:33 pm on Jun 16, 2004 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Maybe there's some reason you're using preg_split which I'm not grasping. Would this do what you need?

preg_match('/^([\$\£]?)([\d]+(\.\d+)?)/',$in, $out);
echo $out[2];

Hester

10:52 am on Jun 24, 2004 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



After stripping out alphabetical characters, so you just have the numbers, I would then try replacing the $ with a space. (If it's not there, nothing happens.) Then I would split the string by ".". This will give you the dollars and the cents in two variables. This way it doesn't matter how long the string is, or if there's a $ at the start.

Eg: (untested!)

$text2 = ereg_replace("$", "", $text);

$text3 = explode(".", $text2);

Now call the values from the array that is $text3:

echo "Dollars = ".$text3[0];
echo "Cents = ".$text3[1]

Any good?