hello im newbie

i have a string example " i want to buy a new car "
and i want to show only 3 words("i want to") from string
can you help me please ?
Does an example project exist for something like this?
thank you

You could use preg_match(). I'm not so good with regular expressions but I hope this'll solve your problem.

$str = "i want to buy a new car";

preg_match("/\S*\s\S*\s\S*/", $str, $result);

echo $result[0]; //prints: I want to

hello v1shwa thanks for reply
yes it's work
but how about i change show five or seven words ?

i dont understand this code "/\S\s\S\s\S*/"
please help

You can use substr

$string = 'I want to buy a new car';

echo substr($string, 0, 9); 

The first param is the string, the second param is where to start and the third param is the length.

This would be a more dynamic approache. You can set all params to variables.

Member Avatar for diafol
<?php
$sentence = 'I want to buy a new car';

function num_words_from_sentence($num, $sentence)
{
    $pattern = str_repeat("\S*\s*",$num);
    preg_match("/$pattern/", $sentence, $result);
    return trim($result[0]);        
}

for($num=1;$num<8;$num++)
    echo $num . ': ' . num_words_from_sentence($num, $sentence) . '<br />';

Result:

1: I
2: I want
3: I want to
4: I want to buy
5: I want to buy a
6: I want to buy a new
7: I want to buy a new car

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.