www.webdeveloper.com
Results 1 to 6 of 6

Thread: string intersect?

  1. #1
    Join Date
    Sep 2008
    Posts
    61

    Red face 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"
    Cheers,
    Artheus

  2. #2
    Join Date
    Aug 2004
    Posts
    244
    Make the strings into arrays of characters and then use http://uk2.php.net/array_intersect

  3. #3
    Join Date
    Sep 2008
    Posts
    61
    Quote Originally Posted by artemis View Post
    Make the strings into arrays of characters and then use http://uk2.php.net/array_intersect
    Yes, as you can see in my question I already know of that method. But aren't there another way?

  4. #4
    Join Date
    Oct 2007
    Location
    Sweden
    Posts
    225
    PHP Code:
    $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$i1) == substr($str2$i1))
            
    $intersect.= substr($str1$i1);



  5. #5
    Join Date
    Sep 2008
    Posts
    61
    ok thanks..
    So the solution I'm seeking does just not exist?

    I mean the "$intersection = $string1 ∩ $string2;"
    would be nice though..

    Thanks again!

    //Artheus

  6. #6
    Join Date
    Oct 2007
    Location
    Sweden
    Posts
    225
    No, that solution does not exist.
    The simplest way would be to make it a function.
    PHP Code:
    $intersection intersect($string1$string2); 

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
HTML5 Development Center



Recent Articles