Php 无法替换空间

Php 无法替换空间,php,str-replace,utf8-decode,Php,Str Replace,Utf8 Decode,我试着从google中取出数字串,并将其清理干净 <?php $q="35 meter in inch"; $query = explode (" ",$q); $googleUrl="http://www.google.com/search?q=$query[0]+$query[1]+$query[2]+$query[3]"; $package = file_get_contents("$googleUrl"); $content = preg_replace('/.*<h2[

我试着从google中取出数字串,并将其清理干净

<?php
$q="35 meter in inch";
$query = explode (" ",$q);  
$googleUrl="http://www.google.com/search?q=$query[0]+$query[1]+$query[2]+$query[3]";
$package = file_get_contents("$googleUrl");
$content = preg_replace('/.*<h2[^>]* style="font-size:138%"><b>|<\/b><\/h2>.*/si', "", $package) ;
$number = explode (" ",$content);
$result = str_replace(' ','',$number[3]);
echo $result;   
?>
然而,我得到的数字有一个空格。
我试着用针或针代替它;。或utf8_编码,解码$content。它们都不起作用。

可能是因为它不是一个真正的空间,尽管看起来像。您可以尝试用正则表达式替换所有\w。

在前面的空格中至于问题的解决方案,最好的答案是使用preg\u replace替换任何不是数字或标点符号的内容;试试这个:

<?php
$q="35 meter in inch";
$query = explode (" ",$q);  
$googleUrl="http://www.google.com/search?q=$query[0]+$query[1]+$query[2]+$query[3]";
$package = file_get_contents("$googleUrl");
$content = preg_replace('/.*<h2[^>]* style="font-size:138%"><b>|<\/b><\/h2>.*/si', "", $package) ;
$number = explode (" ",$content);
$result = preg_replace("/[^\d.]/", '', $number[3]);
echo $result;
?>
但你可能想研究一下如何使用google.com/ig/calculator。它将节省大量带宽,并使您无需拉取完整的谷歌结果页面并替换:


这不是您试图删除的空间,而是在浏览器中不可见的空间。您还可以通过命令行使用php脚本来检查这些内容。您可以使用html实体函数,然后根据该函数进行替换

Trim只删除strings边缘的空白。现在,您怎么能假设google生成的字符串中间有空格!请告诉我,您在生产代码中没有认真这么做。从米到英寸的转换并不是一件困难的事情,它当然比编写代码来解析谷歌的计算器结果要容易。我想,他想提供一个API来在任意X和任意Y之间进行转换,而不仅仅是从米到英寸。我不知道为什么它不把数字上的差距看作是一个空格[非常奇怪的怪癖],但我想我在下面找到了一个解决办法。非常感谢。计算器的速度要快得多。
<?php
$q="35 meter in inch";
$query = explode (" ",$q); 
$googleUrl="http://www.google.com/ig/calculator?q=$query[0]+$query[1]+$query[2]+$query[3]";
$content = file_get_contents("$googleUrl");
preg_match("/rhs:\s\"(.*)\",error/", $content, $number);
$num = explode(" ", $number[1]);
$num = preg_replace("/[^\d.]/", '', $num[0]);
echo $num;
?>