X
X
Xakephp2014-09-24 16:34:58
PHP
Xakephp, 2014-09-24 16:34:58

How to parse text in php without repetition?

We need a php code that parses the text according to this principle

1) кораблик плавал плавал и утонул
2) кораблик плавал плавал и
3) плавал плавал и утонул
4) кораблик плавал плавал
5) плавал и утонул
6) кораблик плавал
7) плавал плавал
8) плавал и
9) и утонул
10) кораблик
11) плавал
12) и
13) утонул
Maybe I even missed it, I don’t know
for sure an example on javascript
jsfiddle.net/petroveg/agwtd8vz

Answer the question

In order to leave comments, you need to log in

4 answer(s)
A
Alexander Kubintsev, 2014-09-25
@Xakephp

$string = 'кораблик плавал плавал и утонул';
$wordArray = explode(' ', $string);
$wordsCount = count($wordArray);
$result = $dupArray = [];


for ($i = 0; $i <= $wordsCount; $i++) {
    for ($j = 0; $j < $i; $j++) {
        $pos = $wordsCount - $i + 1; // length для slice в php относительно offset, а не начала массива
        $stroke = implode(' ', array_slice($wordArray, $j, $pos));

        if (!isset($dupArray[$stroke])) {
            $dupArray[$stroke] = array_push($result, $stroke);
        }
    }
}

echo implode("\n", $result);

S
Sergey, 2014-09-24
Protko @Fesor

How to split text without repetition? - do your best.

D
Denis, 2014-09-25
@cjbars

ideone.com/FPwele
at the entrance Bondarenko Nikolai Petrovich
at the exit:
Bondarenko Nikolai Petrovich
Nikolai Bondarenko Petrovich
Bondarenko Petrovich Nikolai
Petrovich Bondarenko Nikolay
Petrovich Bondarenko
Petrovich Nikolai Bondarenko

X
Xakephp, 2014-09-25
@Xakephp

As an example, I can show this option.

$start = explode(' ', 'кораблик плавал плавал и утонул');

for ($i = 0, $result = array(), $_result = array(), $length = count($start); $i <= $length; $i++) {
    for ($j =0; $j < $i; $j++) {
        $stroke = join(' ', array_slice($start, $j, $j + $length - $i + 1));

        if (!isset($_result[$stroke])) {
            $_result[$stroke] = array_push($result, $stroke);
        }
    }
}

echo join('<br>', $result);

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question