Php 从字符串中删除单引号

Php remove single quote from string

这里让我头疼。 我正在从网站获取数据。

$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]);

这个returns: 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);


?>

我认为转义单引号在 str_replace 中不起作用,因为您使用双引号将针值括起来 - 我很想知道您只需要数字:

$string = preg_replace("/[^0-9]/", "", $match[1]);

作为更可靠的方法。

或者,如果您确信单引号和 $ 是唯一要删除的字符,只需删除数组中的 \,这样您就可以只查找“'”而不是“'”

更新:

为了安全起见,请先尝试删除 htmlentities 和所有标签:

$string = preg_replace("/[^0-9]/", "", strip_tags(html_entity_decode($match[1])));

更新 2:

下面的代码将为您工作并删除代表引号的 HTML 实体。

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>";
echo "<BR>";
$string = preg_replace("/&#?[a-z0-9]+;/i","",$match[1]);
var_dump($string);

对于以后的类似问题,您可以在调试时使用 json_encode / htmlspecialchars 查看实际内容、隐藏内容和所有内容。例如:

echo json_encode(htmlspecialchars($match[1]));

这个

$replacechars = array ("'", "$");

不是这个

$replacechars = array ("\'", "$");