0

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

4
Contributors
4
Replies
15
Views
2 Years
Discussion Span
Last Post by diafol
1

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
0

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

0

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.

0
<?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

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.