简体   繁体   English

如何在 php 中打印句子的前两个单词

[英]How to print first two words of a sentence in php

I wanna print the first two words of a sentence,我想打印一个句子的前两个词,

$txt = "Laravel PHP Node JS";

and expecting the output Laravel PHP并期待 output Laravel PHP

used below snippet is there any other way to simplify it?下面使用的代码片段还有其他方法可以简化它吗?

echo (implode(array_slice(preg_split("/\s+/", $txt), 0, 2),' '));

If with simpler you mean a single function call, you might for example match the first 2 "words" by matching 2 times one or more non whitespace characters with \S+ with preg_match and check if there is a match.如果更简单的意思是单个 function 调用,则可以例如通过将一个或多个非空白字符与\S+preg_match匹配 2 次来匹配前 2 个“单词”,并检查是否存在匹配项。

$txt = "Laravel PHP Node JS";
if (preg_match("/\S+\h+\S+/", $txt, $match)) {
    echo $match[0];
}

Output Output

Laravel PHP

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM