SinB
SinB

Reputation: 3

PHP fails to remove white spaces from a arrays

In my two-dimensional array, the value of array's key [1] is empty, and the value of key name [4], [5], [6], [7], [8] suppose is empty but it show there have String (2) within the arrays values. Well, I think that 2 string maybe is two white spaces, and I tried a variety of methods such as preg_replace, str_replace, trim, array_map, array_filter are not delete or remove the two spaces, all of the functions that i used are not detected that two spaces as a white spaces. Besides that, I also try to use preg_replace, str_replace to replace the two spaces with other string. But it is only the array values and key name [1] have changing ... I dont know why that 2 strings is not recognized as a white space. In addition, I also tried to retype the same arrays in the new php file and debug it, I replace the array values of keys [4], [5], [6], [7], [8] with two spaces. However, the function able to detect that all is a white spaces but the following arrays i post at here the two spaces instead of spaces, obviously they are the same things.

 [1]=>
  array(9) {
    [0]=>
    string(5) "Johor"
    [1]=>
    string(0) ""
    [2]=>
    string(10) "KotaTinggi"
    [3]=>
    string(3) "29*"
    [4]=>
    string(2) " "
    [5]=>
    string(2) " "
    [6]=>
    string(2) " "
    [7]=>
    string(2) " "
    [8]=>
    string(2) " "
  }

Here is the code that i used. The arrays is scraping with curl from a website.

<?php
$ch = curl_init("http://apims.doe.gov.my/v2/hour3_2017-01-31.html");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$page = curl_exec($ch);
$dom = new DOMDocument();
libxml_use_internal_errors(true);
$dom->loadHTML($page);
libxml_clear_errors();
$xpath = new DOMXpath($dom);
$data = array();

$table_rows = $xpath->query('//tr');
foreach ($table_rows as $row => $tr) {
    foreach ($tr->childNodes as $td) {
        $data[$row][] = preg_replace('/\s+/', '', trim($td->nodeValue,"  "));
    }
}
var_dump($data);
 ?>

I also try with this.But all of these are not working. Any pro can help me? or give me some solution.

 $data[$row][] = preg_replace('/\s+/', '', str_replace(' ','',$td->nodeValue));

Upvotes: 0

Views: 377

Answers (2)

Suchit kumar
Suchit kumar

Reputation: 11869

If you are expecting characters and numbers you can use this(keeping * in the string):

preg_replace("/[^a-zA-Z0-9\*]/", "", $td->nodeValue);// this will remove spaces from a proper string also.

or

$data[$row][] = preg_replace("/[^ \w\*]+/", "", $td->nodeValue);// this works better and does not remove spaces

Upvotes: 1

Bambang
Bambang

Reputation: 401

If you take a look at the website, the space is actually an &nbsp; string, so the following should do it:

$data[$row][] = preg_replace('/\&nbsp;/', '', trim($td->nodeValue,"  "));

Upvotes: 0

Related Questions