0

I need to rewrite some code from VB.NET into PHP:

Dim price as String = Regex.Match(html, "id=""price"">&pound;\d+.\d+</span>").Value.Replace("id=""Acashprice"">&pound;", "").Replace("</span>", "")

So I'm trying to begin by getting a match from the regex:

id="price">&pound;\d+.\d+</span>

However, no matter how I format it, I am always told it is invalid – (i.e. no backslashes allowed, or what is p?). I think I may have to use preg_quote in conjunction to preg_match, but I can't get this working either. Any help would be much appreciated.

drspa44
  • 1,041
  • 8
  • 12
  • Show us the PHP code. The regex tries to match a price tag and insert some custom HTML. – silkfire Apr 16 '13 at 21:54
  • You should probably escape the quotes and `<`, `>`, `/` signs in your regex (any special character that has meaning in a regular expression) ! – adeneo Apr 16 '13 at 21:57
  • All The regex does is find the part of the downloaded page that I am interested in. The only code I've got so far is: preg_match("id="Acashprice">£\d+.\d+", $page, $matches); $price = $matches[0]; which I know is wrong. – drspa44 Apr 16 '13 at 21:58
  • 1
    Oh, it's a downloaded page! Better start by reading [**THIS ANSWER FIRST**](http://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags) !!!! – adeneo Apr 16 '13 at 22:00

1 Answers1

2

This should do the job:

preg_match('/(?<=id="price">)&pound;\d+.\d+/', '<span id="price">&pound;55.55</span>', $m);
print_r($m);

Output:

Array
(
    [0] => &pound;55.55
)

A more reliable regex is the following:

$str = '<span id="price">&pound;11.11</span>
<span id="price">&pound;22</span>
<span id="price"> &pound; 33 </span>
<span      id  =  "price"   >      &pound; 44     </span>
<span      id=\'price\'   >      &pound; 55     </span>
<span class="component" id="price"> &pound; 67.89 </span>
<span class="component" id="price" style="float:left"> &pound; 77.5 </span>
<span class="component" id="price" style="float:left:color:#000"> £77.5 </span>
';
preg_match_all('/<span.+?id\s*=\s*(?:"price"|\'price\').*?>\s*((?:&pound;|£)\s?\d+(?:.\d+)?)\s*<\/span>/is', $str, $m);

print_r($m[1]);

Output:

Array
(
    [0] => &pound;11.11
    [1] => &pound;22
    [2] => &pound; 33
    [3] => &pound; 44
    [4] => &pound; 55
    [5] => &pound; 67.89
    [6] => &pound; 77.5
    [7] => £77.5
)
HamZa
  • 14,671
  • 11
  • 54
  • 75