Compare 2 strings

Hi everyone!

I need a help.

I have a 2 strings:
string 1 - “/site/index.php”
string 2 - “/site/category-1/article-1”

How can compare these two strings to get coincidence from the start?
string 1 - “/site/index.php"
string 2 - "
/site/category-1/article-1"
I need a "
/site/

You probably want to use explode()

Thanks, gandalf458!

But these two strings are dinamicaly.
What about this:
string 1 - “**/site/category-1/article-1"
string 2 - "
/site/category-1/**subarticle-1”

What did you get when you tried explode() ?

1 Like

If you are looking for common directory structure then explode on the ‘/’ and compare piece by piece (which is basically what previous posters have said).

Using the explode() function is certainly one way of doing it, but not the best way IMO. As an alternative, you could loop through each character in the strings and compare them:

$str1 = '/site/index.php';
$str2 = '/site/category-1/article-1';

$strBuffer = '';

for ($i = 0; isset($str1[$i], $str2[$i]) && $str1[$i] === $str2[$i]; ++$i)
    $strBuffer .= $str1[$i];

var_dump($strBuffer);

Or you can make use of the bitwise XOR, strspn(), and substr() functions for a more concise solution:

<?php

$str1 = '/site/index.php';
$str2 = '/site/category-1/article-1';

var_dump(substr($str1, 0, strspn($str1 ^ $str2, "\0")));

When two strings are XOR’ed, the characters that are the same are turned into NUL bytes (\0), and so all we have to do is look for the first non-occurrence of this NUL byte character (so-called the ‘mask’) - the strspn() gives us this offset. From there, substr() can be used to get that piece of the string.

It’s a tradeoff between terseness and readability - if you go for the latter solution, be sure to document what it does.

Except… that doesnt work for practicality of what I believe the OP wants.

While a byte-by-byte comparison does work - it only works if your differentiation point is at the CHARACTER level.

Your chosen example works great. But what about this one?

$str1 = '/site/index.php';
$str2 = '/site/inventory/article-1';

Your function would find the answer to be “/site/in”… i dont think thats what the OP wants. (but if it is, then yup, it’s a great one-liner)

Good catch. I knew there was a reason for using explode()…

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.