【问题标题】:Php remove single quote from stringphp从字符串中删除单引号
【发布时间】: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"&gt; 之类的内容的那一天,您的模式将不再起作用。 class="accent no-margin-bottom inline"&gt;foo &lt;span&gt;bar&lt;/span&gt; hello world&lt;/... 也是如此。 PHP Simple HTML DOM Parser 效果不错
  • 数组 ("'", "$");不工作。单引号不会被删除。

标签: php escaping single-quotes


【解决方案1】:

我认为在 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]));

【讨论】:

  • 感谢您的回答,但是,现在单引号已替换为 27。所以现在我看到的是 92785827470 而不是 9'858'470
  • 如果你使用 var_dump($match[1]) 会输出什么?
  • 字符串(20)“ 9'858'470”
  • 啊,我认为您看到的字符串必须是 HTML 编码的。现在更新我的答案...
  • 还是不行。现在我又得到了27。更新了我的代码。可以直接复制。
【解决方案2】:

这个

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

不是这个

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

【讨论】:

猜你喜欢
  • 1970-01-01
  • 2021-11-20
  • 1970-01-01
  • 2013-05-19
  • 1970-01-01
  • 1970-01-01
  • 2021-02-26
  • 1970-01-01
  • 2018-01-19
相关资源
最近更新 更多