Dreni
Dreni

Reputation: 161

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

I use the code above to echo the first word from a sentence. Now I would like to also echo the first two characters from the second word. So that the above echo would result in: Test so

Upvotes: 1

Views: 1413

Answers (5)

F.P
F.P

Reputation: 17831

$myvalue = 'Test some more';
$pos = stripos($myvalue, ' ');
echo substr($myvalue, 0, $pos + 3);

Upvotes: 3

Peon
Peon

Reputation: 8020

<?php
    $myvalue = 'Test some more';

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

    # first two simbols!
    echo ' ' . substr( $arr[1], 0, 2 );
?>

Upvotes: 0

Gerald Versluis
Gerald Versluis

Reputation: 34013

How about a substring?

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

Upvotes: 0

Shehzad Bilal
Shehzad Bilal

Reputation: 2523

use this line :

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

Upvotes: 0

Rob Forrest
Rob Forrest

Reputation: 7450

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

You should probably add a check in to make sure that $arr contains enough words to do this though

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

Upvotes: 1

Related Questions