Php从字符串中删除单引号

问题描述

在这里打断我的头。 我正在从网站获取数据。

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


?>

解决方法

我不认为在 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 ("\'","$");

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...