Answer the question
In order to leave comments, you need to log in
How can you extract the smallest sentence from a string?
How can I extract from a string in php
$string = "Первое предложение. Второе предложение. Тр предл.";
Answer the question
In order to leave comments, you need to log in
Updated answer.
function find_shortest_sentence($text)
{
$sentences = preg_split('/[.!?]\s*/', $text, -1, PREG_SPLIT_NO_EMPTY);
// передали некорректный текст
if (!isset($sentences[0])) {
throw new InvalidArgumentException('Text must contain at least one sentence.');
}
$min = array_shift($sentences);
foreach ($sentences as $sentence) {
if (mb_strlen($sentence) < mb_strlen($min)) {
$min = $sentence;
}
}
return $min;
}
var_dump(
find_shortest_sentence('Первое предложение. Второе предложение. Тр предл.'),
find_shortest_sentence('Первое предложение. Второе предложение. Тр предл')
);
// string(15) "Тр предл"
// string(15) "Тр предл"
In general, regular expressions are not suitable for natural language parsing.
For example, a perfectly valid text from the point of view of the language
Ivan, who had recently moved to the city of N., asked: “How are you?” - and handed a classmate a bouquet of wildflowers. She was embarrassed and blushed, but accepted the bouquet. It was getting dark...you will not parse sentences into any regular expression (and I have not taken this example from Tolstoy yet).
You generally don't even need to store sentences in an array to find the shortest one. The task can also be solved through a state machine, when you go along the line and save the characters to the buffer, and as soon as you find a point, you check that the line in the buffer is shorter than the previous shortest one found.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question