douna1892
2016-10-27 04:59
浏览 42
已采纳

PHP:从file_get_contents字符串测试html标记内的文本字符串

I need to perform a series of tests on a url. The first test is a word count, I have that working perfectly and the code is below:

if (isset($_GET[article_url])){
    $title = 'This is an example title';
    $str = @file_get_contents($_GET[article_url]);
    $test1 = str_word_count(strip_tags(strtolower($str)));
    if($test1 === FALSE) { $test = '0'; }
    if ($test1 > '550') {
        echo '<div><i class="fa fa-check-square-o" style="color:green"></i> This article has '.$test1.' words.';
    } else {
        echo '<div><i class="fa fa-times-circle-o" style="color:red"></i> This article has '.$test1.' words. You are required to have a minimum of 500 words.';
    }       
}

Next I need to get all h1 and h2 tags from $str and test them to see if any contain the text $title and echo yes if so and no if not. I am not really sure how to go about doing this.

I am looking for a pure php means of doing this without installing php libraries or third party functions.

图片转代码服务由CSDN问答提供 功能建议

我需要对网址执行一系列测试。 第一个测试是一个字数,我有完美的工作,代码如下:

  if(isset($ _ GET [article_url])){
 $ title =  '这是一个示例标题'; 
 $ str = @file_get_contents($ _ GET [article_url]); 
 $ test1 = str_word_count(strip_tags(strtolower($ str))); 
 if($ test1 === FALSE  ){$ test ='0';  } 
 if($ test1&gt;'550'){
 echo'&lt; div&gt;&lt; i class =“fa fa-check-square-o”style =“color:green”&gt;&lt; / i&gt  ; 这篇文章有'。$ test1。' 单词。'; 
} else {
 echo'&lt; div&gt;&lt; i class =“fa fa-times-circle-o”style =“color:red”&gt;&lt; / i&gt; 这篇文章有'。$ test1。' 话。 您需要至少500字。'; 
} 
} 
   
 
 

接下来我需要从$ str获取所有h1和h2标签 测试它们以查看是否包含文本$ title并且如果是,则回显yes,否则返回no。 我真的不确定如何去做这件事。

我正在寻找一种纯PHP的方法,无需安装php库或第三方功能。 < / DIV>

  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • dongyizhuang0134 2016-10-27 05:06
    已采纳

    please try below code.

    if (isset($_GET[article_url])){
        $title = 'This is an example title';
        $str = @file_get_contents($_GET[article_url]);
    
        $document = new DOMDocument();
        $document->loadHTML($str);
    
        $tags = array ('h1', 'h2');
        $texts = array ();
        foreach($tags as $tag)
        {
          //Fetch all the tags with text from the dom matched with passed tags
          $elementList = $document->getElementsByTagName($tag);
          foreach($elementList as $element)
          {
             //Store text in array from dom for tags
             $texts[] = strtolower($element->textContent);
          }
        }
        //Check passed title is inside texts array or not using php
        if(in_array(strtolower($title),$texts)){
            echo "yes";
        }else{
            echo "no";
        }
    }
    
    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题