【问题标题】:How could I cut off text after a keyword?如何在关键字后截断文字?
【发布时间】:2011-07-18 06:27:41
【问题描述】:

所以说我会写类似<break> 的东西,它会显示<break> 之前的所有内容

$text = "I like apple pies<break>Do you like Apple pies?";

所以它应该只输出

I like apple pies

【问题讨论】:

    标签: php string substring


    【解决方案1】:

    试试这个:

    $text = "I like apple pies<break>Do you like Apple pies?";
    $texplode = explode('<break>',$text);
    echo $texplode[0];
    

    阅读php explode()

    【讨论】:

      【解决方案2】:
      $text = "I like apple pies<break>Do you like Apple pies?";
      
      list($result) = explode('<break>',$text,2);
      

      【讨论】:

      • list()的优雅
      • list($result) = explode('&lt;break&gt;',$text,2); 更有效,尤其是当字符串在&lt;break&gt; 标记之后很长时(php 不必搜索整个字符串)。
      【解决方案3】:
      $good = substr( $bad, 0, strpos( $bad, "<break>" ) );
      

      【讨论】:

        【解决方案4】:

        作为一个函数:

        function BeforeBreak($input)
        {
            return stristr($input, '<break>', true);
        }
        

        请注意,此功能需要 PHP 5.3.0。

        stristr documentation

        【讨论】:

        • 请注意,这将对&lt;break&gt; 执行不区分大小写的搜索。该功能将是一个好主意,+1。
        • 这样做也是为了接受&lt;BREAK&gt;,但如果区分大小写很重要,请改用strstr
        【解决方案5】:

        这会给你你想要的:

        <?
           $output = strstr($text, '<break>', true);
        ?>
        

        如果出现多次,最好使用

        <?
           $text = 'a<break>b<break>c<break>d';
           $output = explode('<break>', $text);
        
           // the output will be
           // array('a', 'b', 'c', 'd');
        ?>
        

        【讨论】:

        • 请注意,您需要安装 PHP 5.3.0 才能使用before_needle 参数。不错的答案,+1。
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-06-22
        • 1970-01-01
        • 1970-01-01
        • 2014-05-20
        • 1970-01-01
        • 2014-08-03
        相关资源
        最近更新 更多