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/”
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:
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.