0

I have these types of possible content in the strings I'm breaking up:

$string = "$100 USD per year"
$string = "$100USD per year"
$string = "100 USD per year"
$string = "100EUR per year"
$string = "€100EUR per year"
$string = "€100 EUR per year"

This is the regular expression I am using (and it works in Expresso):

$pattern = "/\$?(\d+\.\d+)(\w{0,3})\s(.*)/i";

Basically, I want the end result to be an array like the following:

$arr[0] = "$100" // the "$" optional, also number might be integer or decimal
$arr[1] = "USD";
$arr[2] = "per year";

This is the sample PHP code I'm running but to no avail:

<?php
$content = "$99.37CAD per year";

$pattern = "/\$?(\d+\.\d+)(\w{0,3})\s(.*)/i";

$myArr = preg_split($pattern, $content);

echo "<pre>";
var_dump($myArr);
echo "</pre>";
?>

And the output is:

bool(false)

Can someone please point me in the right direction?

ipruthi
  • 144
  • 2
  • 8

2 Answers2

2

You need to match it not split..

Also the regex should be

  |->required to capture $ or €
  |                |-----------|-------->needed since there can be 0 to many spaces
 --               ---         ---
/.?(\d+(?:\.\d+)?)\s*(\w{0,3})\s*(.*)/
       ----------                
           |
           |
           |->this is needed since it would not always be 55.43..it could be 55
Anirudha
  • 32,393
  • 7
  • 68
  • 89
  • This code is close to working except in the case when there is no currency symbol `$string = 99.37 CAD per year` -- in that case it removes the first character, so `$arr[1] = 9.37`. I marked your reply as answer until I tested further and found that problem. I apologize for that. – ipruthi Dec 01 '12 at 13:03
2

The problem is that the SPACE between the price and the EUR/CAD/USD, is not optional. So you just have to add a * to it, like \s*. With that you will tell RegEx that that space is optional so it can be or not.

Another thing is that you must match, not split. With the decimal digits optional.

DEMO Regex: [$€]?(\d+(?:\.\d+)?)\s*(\w{0,3})\s*(.*)

Javier Diaz
  • 1,791
  • 1
  • 17
  • 25
  • Thanks! This worked, except I had to escape the $ and euro sign, like so: `/[\$\€]?(\d+(?:\.\d+)?)\s*(\w{0,3})\s*(.*)/` – ipruthi Dec 01 '12 at 13:05