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
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().
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.
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.
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.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With