Qqwy
Qqwy

Reputation: 5629

PHP: Compare the start of two strings

I am wondering if there is a simple way to, in PHP, compare two strings and returns the amount of characters they have in common from the start of the string.

An example:

$s1 =  "helloworld";
$s1 =  "hellojohn";

These two strings both start with 'hello', which means that both strings have the first 5 characters in common. '5' is the value I'd like to recieve when comparing these two strings.

Is there a computationally fast way of doing this without comparing both strings as arrays to eachother?

Upvotes: 1

Views: 962

Answers (4)

simon.denel
simon.denel

Reputation: 788

function commonChars($s1, $s2) {
    $IMAX = min(strlen($s1), strlen($s2));
    for($i = 0; $i < $IMAX; $i++)
        if($s2[i] != $s1[i]) break;
    return $i;
}

Upvotes: 4

hurrtz
hurrtz

Reputation: 1993

If it's the similarity of the strings you wish to get and not just the actual number of identical characters, there are two functions for that:strcmp and levenshtein. Maybe they suit your goal more than what you asked for in this question.

Upvotes: 1

000
000

Reputation: 27227

If the strings are really big, then I would write my own binary search. Something similar to this totally untested code that I just dreamed up.

function compareSection($start, $end, $string1, $string2) {
  $substr1 = substr($string1, $start, $end-$start);
  $substr2 = substr($string2, $start, $end-$start);
  if ($substr1 == $substr2) return $end;
  if ($firstMatches = compareSection(0, $end/2, $substr1, $substr2)) {
    return $start + $firstMatches;
  if ($lastMatches = compareSection($end/2, $end, $substr, $substr2)) {
    return $start+$lastMatches;
  }
}

Upvotes: 1

Rob Avery IV
Rob Avery IV

Reputation: 3720

From my knowledge, I don't think there is a built in function for something like this. Most likely, you will have to make your own.

Shouldn't be too hard. Just loop both strings by index by index until you don't find a match that doesn't match. However far you got is the answer.

Hope that helps!

Upvotes: 0

Related Questions