【问题标题】:PHP How to output a string that comes after a certain keyword in a long textPHP如何在长文本中输出某个关键字之后的字符串
【发布时间】:2017-11-21 09:30:08
【问题描述】:

基本上,我想获取一个长文本文件(源代码),在该文件中找到一个特定的关键字,然后打印出该关键字之后的接下来的 400 个字符。我不希望关键字之后的所有内容,因为最终会超过 20,000 个字符。 如果可以的话,我想在那里划定它们(这是我最初尝试做的但失败了)它很快变得非常混乱。如果我只能得到 400 个字符,那么我可以将其保存到一个文本文件中,然后分隔该 400 个字符的文本文件。

我现在的代码是:

        <?php
            $website = $_GET["website"]; //I'm pulling the website from a form
            $contents = file_get_contents($website));
            $del = 'keyword'; 
            $search = preg_quote($del, '/');
            $search = "/^.*$search.*\$/m";
            if(preg_match_all($search, $contents, $found)){
                echo implode("\n", $found[0]);
            }else{}
        ?>

问题是上面打印出关键字之后的所有内容,我什至无法获取我得到的内容并进一步界定它。我的想法越多,我就越能从解决方案中获得更多。 非常感谢任何帮助。

【问题讨论】:

  • 源代码是HTML还是XML?

标签: php delimiter


【解决方案1】:

您可以使用substr($your_string, 0, 400) 仅获取从字符串开始的 400 个字符。

使用此方法的语法是substr(string,start,length)

【讨论】:

    【解决方案2】:

    您可以通过 strposstrlensubstr 的组合来执行此操作。您不需要任何正则表达式来执行此操作,并且您不应该使用它,因为正则表达式通常慢如死亡。尽可能避免使用正则表达式,只有在没有其他答案时才使用它。

    <?php
    $website = $_GET["website"]; //I'm pulling the website from a form
    $contents = file_get_contents($website));
    $del = 'keyword';
    
    //get the index of the end of your split value
    //this is the character index of your keyword, plus the length of the keyword,
    //so it will start collecting the next bit at the end of the first occurance of keyword.
    $index = strpos($contents, $del) + strlen($del);
    
    //get the text you want
    $text = substr($contents, $index, 400);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-07-08
      • 2015-03-04
      • 2015-04-10
      • 2013-04-06
      • 2020-02-14
      相关资源
      最近更新 更多