计算文件中两对字符串之间的最大距离(位置)



我想计算文件中两个字符串之间的最大距离。

Str1和str2可以相同,比如max_dist('.','.',$text)

比方说:public static function max_dist($str1, $str2, $text)

文本就像维基百科中的一样,例如:

虽然不是明确的无政府主义者,但他们是按普通人组织的民主,体现了激励了许多人的抵抗精神英语辛迪加主义者。

我想找到','和'之间的最大距离。'在整个文件中。请注意,"、"one_answers"。"在所有文本中重复,可以成对找到,也可以不成对找到。

该示例应返回125作为第一个逗号和点之间的距离。

我正在开发以下代码,但到目前为止,只有在没有重复字符串的情况下才能工作:

public static function max_dist($str1, $str2, $f)
{
$len = strlen($f);
$max_dist = 0;
$pos_a = 0; $pos_b = 1;
while (true) {
$a = strpos($f, $str1, $pos_a);
$b = strpos($f, $str2, $pos_b);
if (!($a && $b)) break;
if ($a == $b)
$b = strpos($f, $str2, $a + 1);
if (!$a || !$b) continue;     
//if() 
$abs = abs($a - $b);
if ($abs > $max_dist) $max_dist = $abs;
$pos_a = $a + 1;
$pos_b = $b + 1;
}
return $max_dist;
}

有什么想法吗?我找到了函数strstr.php,但它没有偏移选项


编辑以澄清:

假设文本如下:

金雀花王朝(1154-1485)是所有王朝的王室从亨利二世到理查三世的英国国王,包括安格文王朝国王以及兰开斯特和约克的家族。除了国王的传统司法、封建和军事角色金雀花王朝对王国负有责任,其基础是复杂的司法系统。

您的函数(@bogdan)返回所有函数中的最大值,即:246。我想计算所有的最大值,但按对计算,在这种情况下应该是:139(judicial,system.)

我认为您的函数太复杂了。只需将strposstrrpos:一起使用

$string = "Though not explicitly anarchist, they organized by rank and file democracy, embodying a spirit of resistance that has inspired many Anglophone syndicalists.";
function max_dist($needle1, $needle2, $string)
{
$first = strpos($string, $needle1);
$last = strrpos($string, $needle2);
return $last - $first;
}
echo max_dist(',', '.', $string);

如果.可以在,之前,您可能需要在第二次检查时交换参数。或者使用abs函数。

更新

如果我理解正确的话。然后您应该保留未处理的字符串:

$string = "The House of Plantagenet (1154–1485) was the royal house of all the English kings from Henry II to Richard III, including the Angevin kings and the houses of Lancaster and York. In addition to the traditional judicial, feudal and military roles of the king, the Plantagenets had duties to the realm that were underpinned by a sophisticated justice system.";
function max_dist($needle1, $needle2, $string)
{
$distances = [];
$string_left = $string;
while (strpos($string_left, $needle1) !== false && strpos($string_left, $needle2) !== false) {
$first = strpos($string_left, $needle1);
$last = strpos($string_left, $needle2);
$distance = abs($last - $first);
$distances[] = $distance;
$offset = max([$first, $last]);
$string_left = substr($string_left, $offset);
}
return $distances;
}
echo max(max_dist(',', '.', $string));

最新更新