R
R
RusTorg2015-08-20 11:33:09
PHP
RusTorg, 2015-08-20 11:33:09

How can you extract the smallest sentence from a string?

How can I extract from a string in php

$string = "Первое предложение. Второе предложение. Тр предл.";

Each sentence in an array compare them by length and output the shortest one or just wrap the shortest one in a span?
It should be noted that the last sentence may not end with a punctuation mark.

Answer the question

In order to leave comments, you need to log in

3 answer(s)
M
Mikhail Osher, 2015-08-20
@RusTorg

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) "Тр предл"

A
Alexey Ukolov, 2015-08-20
@alexey-m-ukolov

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).
Therefore, you first need to create a formal set of rules and restrictions that your text must obey, and only then can we help you create a regular expression for this set.

V
Vladimir Martyanov, 2015-08-20
@vilgeforce

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 question

Ask a Question

731 491 924 answers to any question