开发者

PHP variables not equal

I am still relatively new to coding with PHP, though I am familiar with a few other languages, so I decided to fool around with it a bit.

Basically I have been playing with regex and Web scraping, and am working on a script to parse some information from a site. I am getting the information fine, but when I try to compare the values in one of my arrays to a string, it is not coming up equal even though the values show the same and are the same data type. Here is an example of what I am working with.

Here I am simply trying to get my values compared by retrieving a set of values from a site and then moving them to a 1d array. Assuming that the value of array[0] = "Value", it should be equal to $str. I have checked with gettype() and both $tmp and $str are strings, yet they do not register as equal. I have also tried with current() values in my array (which would actually be better for my purposes) but it is the same.

What I actually need to do is locate a value in my array and compare it to $str. If it matches, I need to set a variable to the previous value in the array.

$html = file_get_contents("http://www.si开发者_如何学Cte.com");    
$str = "Value";

preg_match_all ('/<td class=\"name\">(.*?)<\/td>/s', $html, $return, PREG_PATTERN_ORDER);

           for ($ii = 0; $ii < count($return[0]); $ii++) {
                 $array[$ii] = $return[0][$ii];
           }


            $tmp = $array[0];

            if ($tmp == $str) {
              echo "yes";
            }


The result handling is a bit off.

 preg_match_all ('#<td class="name">(.*?)</td>#s', $html, $return);

You will get the (.*?) matches in $return[1]. And you don't need to iterate over that. Just use:

 $array = $return[1];

And then you probably want to compare all entries in the result list, not just the first:

 foreach ($array as $i=>$tmp) {
     if ($tmp == $str) {
          echo "yes";
     }
 }

To then get the previous(?) value, simply access $array[$i-1] (in place of the echo above).


$tmp will always include the <td...>...</td> tags in the code you are using, you probably want to replace

for ($ii = 0; $ii < count($return[0]); $ii++) {
    //Matches of whole pattern (not just 1st group)
    $array[$ii] = $return[0][$ii];
}

with

$array=$return[1]; //array of matches of the 1st group

because there is also no need for the for-loop...

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜