/    Sign up×
Community /Pin to ProfileBookmark

string intersect?

Hi!

I’m wondering about if there is an easy way of calculating the intersection of the letters in two strings, with PHP?

I know I could make arrays of the strings by exploding them, and then use the array_intersect, and then imploding them to get the value I’m after.. But it seems like an unnecessary amount of steps to get that value..

So.. and “example” of what I’m after:

[CODE]
$string1 = “mama”;
$string2 = “papa”;

$intersection = $string1 ∩ $string2;

echo $intersection; //I want this to write “aa”
[/CODE]

Cheers,
Artheus

to post a comment
PHP

5 Comments(s)

Copy linkTweet thisAlerts:
@artemisMay 15.2009 — Make the strings into arrays of characters and then use http://uk2.php.net/array_intersect
Copy linkTweet thisAlerts:
@artheusauthorMay 15.2009 — Make the strings into arrays of characters and then use http://uk2.php.net/array_intersect[/QUOTE]

Yes, as you can see in my question I already know of that method. But aren't there another way?
Copy linkTweet thisAlerts:
@QuidamMay 15.2009 — [code=php]
$str1 = "mama";
$str2 = "papa";

if (strlen($str1) > strlen($str2))
$size = strlen($str1);
else
$size = strlen($str2);

$intersect = null;

for ($i=0; $i<$size; $i++) {

if (substr($str1, $i, 1) == substr($str2, $i, 1))
$intersect.= substr($str1, $i, 1);

}
[/code]
Copy linkTweet thisAlerts:
@artheusauthorMay 15.2009 — ok thanks..

So the solution I'm seeking does just not exist?

I mean the "$intersection = $string1 &#8745; $string2;"

would be nice though..

Thanks again!

//Artheus
Copy linkTweet thisAlerts:
@QuidamMay 16.2009 — No, that solution does not exist.

The simplest way would be to make it a function.
[code=php]$intersection = intersect($string1, $string2);[/code]
×

Success!

Help @artheus spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 5.18,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @AriseFacilitySolutions09,
tipped: article
amount: 1000 SATS,

tipper: @Yussuf4331,
tipped: article
amount: 1000 SATS,

tipper: @darkwebsites540,
tipped: article
amount: 10 SATS,
)...