-6

Here's my string: "N/A - -0.09%" (the double quotes are included and part of the string I want to dissect)

Here's my code:

$url = 'abc123.php';    
$data = file_get_contents($url);  //$data contains "N/A - -0.09%" (the string to parse)

$regex = '/""/';
preg_match($regex,$data,$match);
var_dump($match);

How do I isolate everything after the first hyphen, but before the % sign?

I know for a fact that the string will ALWAYS have " "N/A - " in front, and I only want to extract the number with its negative sign if it's negative.

I want to assign the number -0.09 to a variable. The number may be positive or negative. If it's positive there will be no hypen, eg. 0.123. If it's negative there will be a second hyphen in addition to the first, eg. -2.5 .

Please help me formulate the regex part to isolate -0.09 into a variable, say $number. THANK YOU SO!

Alan Moore
  • 73,866
  • 12
  • 100
  • 156
MrPatterns
  • 4,184
  • 27
  • 65
  • 85

1 Answers1

1

I wouldn't use a regex here, I'd just remove the two quotes (replacing " with nothing using str_replace()), then split the string into words (using explode() with ' ' as the delimiter), then grab the last "word" using array_pop().

url = 'abc123.php';    
$data = file_get_contents($url);  //$data contains "N/A - -0.09%" (the string to parse)

$match = array_pop(explode(' ', str_replace("\"", '', $data)));
echo $match . "\n";
Ben Lee
  • 52,489
  • 13
  • 125
  • 145
  • Hi Ben, Thanks for the helpful comment. I didn't know about explode and array_pop(). This does EXACTLY what I was looking for and I learned 2 new things. THANK YOU! – MrPatterns Dec 03 '11 at 13:32
  • Ben, I had a followup question about the output. I get this: string(6) "-0.09%". How do I remove the string(6) and double quotes and percentage sign surrounding the number I want (in this case it's -0.09). – MrPatterns Dec 03 '11 at 13:37
  • 1
    That's just because you are using `var_dump`. That's not what you want. var_dump is a structured output. If you just want to output the string, use `echo`. – Ben Lee Dec 03 '11 at 13:51
  • 1
    I updated my answer to show what I mean. – Ben Lee Dec 03 '11 at 13:51
  • Ben..I see what you mean now. Thank you for your help! – MrPatterns Dec 03 '11 at 14:04