在 PHP 中获取句子的第一个单词和第二个单词中的两个字符


Get first word of a sentence and two characters from second word in PHP?

$myvalue = 'Test some more';
$arr = explode(' ',trim($myvalue));
echo $arr[0]; // will print Test

我使用上面的代码来回显句子中的第一个单词。现在我也想呼应第二个词中的前两个字符。因此,上述回声将导致:测试所以

$myvalue = 'Test some more';
$pos = stripos($myvalue, ' ');
echo substr($myvalue, 0, $pos + 3);
echo $arr[0] . " " . substr($arr[1],0,2);

您可能应该添加一个签入以确保$arr包含足够的单词来执行此操作

if(count($arr) >= 2)
{
    // do stuff here
}

使用以下行:

echo $arr[0] . substr($arr[1],0,2);

子字符串怎么样?

$myvalue = 'Test some more';
$arr = explode(' ',trim($myvalue));
echo $arr[0] . ' ' . substr($arr[1], 0, 2); // will print Test so
<?php
    $myvalue = 'Test some more';
    $arr = explode(' ',trim($myvalue));
    echo $arr[0]; // will print Test
    # first two simbols!
    echo ' ' . substr( $arr[1], 0, 2 );
?>