Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Php String union and intersection

Tags:

string

php

I am stuck at this problem. I have an array like :

Array ( [0] => usb [1] => usb pc [2] => pc [3] => camera [4] => camera 168 [5] => 168 )

I want to output only two entries from the above array which contains [usb pc] and [camera 168] because their disintegration already have other elements so no need of those elements.

another example

[kaushik]
[kaushik is]
[kaushik is great]
[is]
[is great]
[great]

This should out put only [kaushik is great] element.

another example :

[usb]
[pc]
[cam 168]
[cam]
[168]

This should out put [usb] [pc] and [cam 168] elements.

The above problem is a part of one problem in which i want to find out the number of split points in a string.

For example string is : USB PC CAMERA DOWNLOAD 168

keyword : USB PC CAMERA 168

here in the string the keyword is split by the word DOWNLOAD if you can guess.

So number of splits = 1

again if we take string: USB of our PC the CAMERA DOWNLOAD 168

here the keyword is split by "of our" "the" and "DOWNLOAD"

hence number of splits = 3

like image 630
user3475546 Avatar asked Jun 09 '26 11:06

user3475546


1 Answers

Have tested it, and it seems to work fine. (Fixed bug with dupes)

    <?php
// $a = array( 'kaushik', 'kaushik is', 'kaushik is great', 'is', 'is great', 'great' );
$a = array('usb', 'pc', 'cam 168', 'cam', '168', 'cam 168');

$a = array_unique($a);
$s = count($a);
$p = array();

foreach ($a as $key => $b)
{
    $x = 0;
    for ($i = 0; $i < $s; $i++)
    {
        if ($key == $i) continue;

        $c = $a; unset($c[$key]);
        if (strpos($c[$i], $b) === false) $x++;

        if ($x == $s - 1) array_push($p, $key);
    }
}

foreach ($p as $o => $value) {
    echo $a[$value]. ' ';
}
?>

In action here

like image 106
Ed T. Avatar answered Jun 11 '26 04:06

Ed T.