ds000001
2016-07-21 14:21
浏览 57
已采纳

我如何在PHP中创建一个字符串对象的数组?

i want to create an array of variable $link to get all the links in array so that i can process them simultaneously outside curly braces

include("simple_html_dom.php");


$html = file_get_html($url);

$i=0;
$linkObjs = $html->find('h3.r a'); 
foreach ($linkObjs as $linkObj) 
{
    $title = trim($linkObj->plaintext);
    $link  = trim($linkObj->href);

    //if it is not a direct link but url reference found inside it, then extract
    if (!preg_match('/^https?/', $link) && preg_match('/q=(.+)&sa=/U', $link, $matches) && preg_match('/^https?/', $matches[1])) 
    {
        $link = $matches[1];
    } else if (!preg_match('/^https?/', $link)) { // skip if it is not a valid link
        continue;
    }

   $descr = $html->find('span.st',$i); // description is not a child element of H3 thereforce we use a counter and recheck.
   $i++;   
}
  • 写回答
  • 好问题 提建议
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • dqjcb132285 2016-07-21 14:27
    已采纳

    Create an array and push matches.

    include("simple_html_dom.php");
    
    
    $html = file_get_html($url);
    
    $links = array();
    $i=0;
    $linkObjs = $html->find('h3.r a'); 
    foreach ($linkObjs as $linkObj) 
    {
        $title = trim($linkObj->plaintext);
        $link  = trim($linkObj->href);
    
    
      //   if it is not a direct link but url reference found inside it, then extract
    if (!preg_match('/^https?/', $link) && preg_match('/q=(.+)&sa=/U', $link, $matches) && preg_match('/^https?/', $matches[1])) 
    {
       array_push($links, $link);        
     } else if (!preg_match('/^https?/', $link)) { // skip if it is not a valid link
       continue;
       }
    
    $descr = $html->find('span.st',$i); // description is not a child element of H3 thereforce we use a counter and recheck.
    $i++;   
    }
    
    已采纳该答案
    评论
    解决 无用
    打赏 举报
  • dongshan3806 2016-07-21 14:28

    Just declare a array variable, and add it to use it later.

    Before Loop,

    $myLinks = [];
    

    And, Just after this line,

     $link = $matches[1];
     $myLinks[] = $link;
    

    Now, you can use the array $myLinks, Hope this was what you needed.

    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题