Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding matching portions of two strings in PHP

I'm looking for a simple way to find matching portions of two strings in PHP (specifically in the context of a URI)

For example, consider the two strings:

http://2.2.2.2/~machinehost/deployment_folder/

and

/~machinehost/deployment_folder/users/bob/settings

What I need is to chop off the matching portion of these two strings from the second string, resulting in:

users/bob/settings

before appending the first string as a prefix, forming an absolute URI.

Is there some simple way (in PHP) to compare two arbitrary strings for matching substrings within them?

EDIT: as pointed out, I meant the longest matching substring common to both strings

like image 218
ubermensch Avatar asked Nov 25 '10 23:11

ubermensch


People also ask

How do I check if two strings are similar in PHP?

The strcmp() function compares two strings. Note: The strcmp() function is binary-safe and case-sensitive. Tip: This function is similar to the strncmp() function, with the difference that you can specify the number of characters from each string to be used in the comparison with strncmp().

Which function returns the number of matching characters of two string in PHP?

PHP | similar_text() Function. The similar_text() function is a built-in function in PHP. This function calculates the similarity of two strings and returns the number of matching characters in the two strings.

Can you use == to compare strings in PHP?

The most common way you will see of comparing two strings is simply by using the == operator if the two strings are equal to each other then it returns true. This code will return that the strings match, but what if the strings were not in the same case it will not match.

How can I get part of a string in PHP?

Answer: Use the PHP substr() function The PHP substr() function can be used to get the substring i.e. the part of a string from a string. This function takes the start and length parameters to return the portion of string.


1 Answers

Assuming your strings are $a and $b, respectively, you can use this:

$a = 'http://2.2.2.2/~machinehost/deployment_folder/';
$b = '/~machinehost/deployment_folder/users/bob/settings';

$len_a = strlen($a);
$len_b = strlen($b);

for ($p = max(0, $len_a - $len_b); $p < $len_b; $p++)
    if (substr($a, $len_a - ($len_b - $p)) == substr($b, 0, $len_b - $p))
        break;

$result = $a.substr($b, $len_b - $p);

echo $result;

This result is http://2.2.2.2/~machinehost/deployment_folder/users/bob/settings.

like image 114
cambraca Avatar answered Sep 30 '22 12:09

cambraca