问题
I feel like I am missing something. I am using the following code to pull some numbers from a table. As simple as it looks, I cannot seem to get anything to print. I am placing my code and an example of the table below. Please help me find my error. I want it to print out only the numbers in each cell.
//gets the site
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'http://site.org');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$response = curl_exec($ch);
//parse the data
preg_match_all('/<td align=right>(\d+?)</td>/', $response, $matches2);
//prints the parsed data
print_r($matches2[0]);
Here is a sample of the table.
<center><table border=1><tr><th align=left>Address</th><th width=50>0</th><th width=50>1</th><th width=50>2</th><th width=50>3</th><th width=50>4</th><th width=50>5</th><th width=50>6</th><th width=50>7</th><th width=50>8</th><th width=50>9</th></tr><tr><td>N7:0</td>
<td align=right>1</td>
<td align=right>1</td>
<td align=right>1</td>
<td align=right>99</td>
<td align=right>0</td>
<td align=right>0</td>
<td align=right>0</td>
<td align=right>0</td>
<td align=right>0</td>
<td align=right>0</td>
</tr><tr><td>N7:10</td>
<td align=right>0</td>
<td align=right>7300</td>
<td align=right>16400</td>
<td align=right>3300</td>
<td align=right>2200</td>
<td align=right>6100</td>
<td align=right>28000</td>
<td align=right>18000</td>
<td align=right>0</td>
<td align=right>0</td>
</tr></table></center><hr width=25% align=center>
回答1:
The PHP-Error-Reporting should have given you a hint. I strongly advice to set error_reporting to E_ALL and display_errors to "on" during development.This would have given you a hint, as to why you don't get any results:
PHP Warning: preg_match_all(): Unknown modifier 't'
So you should add an escape to the slash inside your regex, because, you use it as delimiter.
preg_match_all('/<td align=right>(\d+?)<\/td>/', $response, $matches2);
As always, I would suggest, using another delimiter and thus keep your regex more readable. I normally choose "~". This would look like:
preg_match_all('~<td align=right>(\d+?)</td>~', $response, $matches2);
回答2:
Try this:
preg_match_all('/<td align=right>(\d+?(\.\d+)?)<\/td>/', $response, $matches2);
print_r($matches2[1]);
Notice the forward slash in the closing TD tag is now escaped.
来源:https://stackoverflow.com/questions/24312196/php-using-curl-and-preg-match-all