Вывод совпадения в строке PHP
У нас есть две строки "строка" и "сорока". Нужно вывести самое длинное совпадение символов или массив со всеми совпадениями символов, которые больше одного. Например в данном случае, должно вывести "рока" - это самое длинное совпадение. Если строки "Ваптос" и "Запросы", результат будет ["ап", "ос"] - два совпадения по два символа.
$word1 = 'Kangaroo';
$word2 = '/' . 'angar' . '/';
$matches = array();
echo 'Longest common part: ' . preg_match_all($word2, $word1, $matches)."\n";
var_dump( $matches[0] );
Результат:
Longest common part: 1
array(1) {
[0]=>
string(5) "angar"
}
Есть мысли ?
Ответы (1 шт):
Автор решения: Евгений Тихии
→ Ссылка
Найдет все совпадения в строках.
Class:
class FindSubStrings {
/**
* Properties for hold the strings.
*
* @var string $firstString
* @var string $secondString
*/
protected $firstString = '';
protected $secondString = '';
/**
* Assign the compare strings.
*
* @param string $first
* @param string $second
*
* @return array
*/
public function __construct (string $firstStr, string $secondStr) {
$this->firstString = str_replace (['"', '/'], ["'", '-'], strtolower ($firstStr));
$this->secondString = str_replace (['"', '/'], ["'", '-'], strtolower ($secondStr));
}
/**
* Service method for explode the string to different length parts.
*
* @param string $string
*
* @return array
*/
protected function getStringsParts (string $string): array {
mb_internal_encoding ("UTF-8");
$stringParts = [];
for ($i = 2; $i <= iconv_strlen ($string); $i++) {
for ($j = 0; $j < iconv_strlen ($string); $j++) {
$stringParts[] = mb_substr ($string, $j, $i);
}
}
return $stringParts;
}
/**
* Method, which should return an array with all match which was
* found in the strings.
*
* @param void
*
* @return array
*/
public function getMatches (): array {
$firstPartsArray = $this->getStringsParts ($this->firstString);
$secondPartsArray = $this->getStringsParts ($this->secondString);
$matches = array_unique (array_intersect ($firstPartsArray, $secondPartsArray));
foreach ($matches as $index1 => $item1) {
foreach ($matches as $index2 => $item2) {
if (iconv_strlen (trim ($item2)) > 1) {
if (preg_match ("/($item2)/", $item1) and iconv_strlen ($item2) < iconv_strlen ($item1)) {
unset ($matches[$index2]);
}
} else
unset ($matches[$index2]);
}
}
return $matches;
}
}
Usage:
/**
* Choose and sat any strings.
*
* @var string $string1
* @var string $string2
*/
$string1 = "Football is my favorite game";
$string2 = "footcort is my best place for watch a ball games.";
/**
* Create instance of FindSubStringsClass.
*
* @var \FindSubStrings $findSubStrings
* @var array $matches
*/
$findSubStrings = new FindSubStrings ($string1, $string2);
$matches = $findSubStrings->getMatches ();
/**
* Echo the result.
*/
echo '<pre>';
print_r ($matches);
Output:
Array
(
[18] => or
[56] => foot
[88] => ball
[107] => game
[148] => is my
)