Skip to content

Instantly share code, notes, and snippets.

@havvg
Created April 5, 2013 15:08
Show Gist options
  • Save havvg/5320031 to your computer and use it in GitHub Desktop.
Save havvg/5320031 to your computer and use it in GitHub Desktop.
Calculate the common prefix of two strings.
<?php
// The smallest length of all strings, limited at 10 characters.
$limit = min(strlen($origin), strlen($destination), 10);
// Increment $i as long as the characters at its ($i) position match.
for ($i = 0; $i < $limit && $origin[$i] === $destination[$i]; $i++);
// $i now contains the length of the common prefix
@harkalygergo
Copy link

harkalygergo commented Feb 19, 2018

This is my solution:

function common_prefixes($str1, $str2)
{
	$i = 0;
	$str = '';
	$str1_array = str_split($str1);
	$str2_array = str_split($str2);
	for($i = 0; $i<count($str1_array); $i++)
	{
		if($str1_array[$i]!==$str2_array[$i])
		{
			return $str;
		}
		else
		{
			$str .= $str1_array[$i];
		}
	}
}
function count_common_prefixes($str1, $str2)
{
	return strlen(common_prefixes($str1, $str2));
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment