【问题标题】:How to save just the first 4 words in a string?如何只保存字符串中的前 4 个单词?
【发布时间】:2013-09-20 00:25:23
【问题描述】:

所以基本上我硬了一个非常大的字符串,我只想保存它的前 4 个单词。

我几乎可以做到这一点,尽管有些情况会破坏它。

这是我当前的代码:

$title = "blah blah blah, long paragraph goes here";
//Make title only have first 4 words
$pieces = explode(" ", $title);
$first_part = implode(" ", array_splice($pieces, 0, 4));
$title = $first_part;
//title now has first 4 words

破坏它的主要案例是line-breaks。如果我有这样的段落:

Testing one two three
Testing2 a little more three two one

$title 将等于 Testing one two three Testing2

另一个例子:

Testing
test1
test2
test3
test4
test5
test6
sdfgasfgasfg fdgadfgafg fg

标题等于 = Testing test1 test2 test3 test4 test5 test6 sdfgasfgasfg fdgadfgafg fg

由于某种原因,它正在抓取下一行的第一个单词。

有人对如何解决这个问题有任何建议吗?

【问题讨论】:

    标签: php string explode implode


    【解决方案1】:

    这可能有点老套,但我会尝试只使用 str_replace() 来消除任何换行符。

    $titleStripped = str_replace('\n', ' ', $title);
    $pieces - explode(' ', $title);
    

    但取决于您的应用程序和预期数据。如果您期望的不仅仅是换行符,请使用 preg_replace。无论哪种方式,在爆炸之前准备好数据。

    【讨论】:

    • 好主意,虽然数据基本上可以是任何东西。甚至可以在下一个单词之前有 5 个换行符。
    • 其实,如果我使用我的方法,这可能会很好,但是用空格替换换行符,然后再次使用我的方法
    • 最终使用您的逻辑来回答我的问题,我创建了一个 preg_match 来替换任何换行符。对于那些想知道我如何解决它的人,我将其放在代码的开头:$title = preg_replace( "/\r|\n/", " ", $title);
    【解决方案2】:

    试试这个:

    function first4words($s) {
        return preg_replace('/((\w+\W*){4}(\w+))(.*)/', '${1}', $s);    
    }
    

    https://stackoverflow.com/a/965343/2701758

    【讨论】:

      【解决方案3】:

      试试这个(未经测试的代码):

      //--- remove linefeeds
      $titleStripped = str_replace('\n', ' ', $title);
      //--- strip out multiple space caused by above line
      preg_replace('/ {2,}/g',$titleStripped );
      //--- make it an array
      $pieces = explode( ' ', $titleStripped );
      //--- get the first 4 words
      $first_part = implode(" ", array_splice($pieces, 0, 4));
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2022-06-22
        • 1970-01-01
        • 2011-12-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-03-07
        相关资源
        最近更新 更多