【发布时间】:2020-12-31 11:28:26
【问题描述】:
在这里打破我的头。 我正在从网站获取数据。
$page = file_get_contents('https://somepage.com/example');
我用下面的搜索数据我要过滤掉的信息:
preg_match('/class="accent no-margin-bottom inline">(.*?)</', $page, $match);
我得到的价值是:$ 9'858'470,这就是我想要的。 我希望这是一个字符串值。由于我想将此数据插入数据库,因此我想删除 $ 符号和单引号。 我正在尝试这样:
$replacechars = array ("\'", "$");
echo $string = str_replace($replacechars, "", $match[1]);
返回:9'858'470
我不明白为什么我仍然看到单引号。
我刚放的时候
$string2 = "9'858'470";
$replacechars = array ("'", "$");
echo $string2 = str_replace($replacechars, "", $string2);
它有效。网页过滤出来的值有问题吗?
更新了我的代码。
<?php
require 'simple_html_dom.php';
$html = file_get_html('https://swissborg.com/chsb-overview');
$replacechars = array ("'", "$");
preg_match('/class="accent no-margin-bottom inline">(.*?)</', $html, $match);
//echo "<BR>";
var_dump($match[1]);
echo "<BR>";
$string = preg_replace("/[^0-9]/", "", strip_tags(html_entity_decode($match[1])));
var_dump($string);
?>
【问题讨论】:
-
你不需要在双引号字符串中转义单引号,尝试使用
array ("'", "$"); -
旁注:不要使用 RegEx 解析 HTML。响应将具有
class="accent no-margin-bottom inline" id="42">之类的内容的那一天,您的模式将不再起作用。class="accent no-margin-bottom inline">foo <span>bar</span> hello world</...也是如此。 PHP Simple HTML DOM Parser 效果不错 -
数组 ("'", "$");不工作。单引号不会被删除。
标签: php escaping single-quotes