Search code examples
phpstr-replaceutf8-decode

Unable to str_replace space


I try to pull out the number string from google and clean it up.

<?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;   
?>

however, the number i've got has a space. I tried to replace it with needles " " or "&nbsp ;". Or utf8_encode, decode $content. None of them works.


Solution

  • As for the solution to your problem, the best answer is to replace anything that is not a number or punctuation using preg_replace(); Try this:

    <?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;
    ?>
    

    But you may want to look into using google.com/ig/calculator. It should save a lot on bandwidth and save you having to pull a full Google Results page and replace on it: http://www.google.com/ig/calculator?hl=en&q=35%20meter%20in%20inch

    <?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;
    ?>