1

I have 2 strings :

Ass. Présentation Chiara D29,5cm
Ass. Présentation Chiara Anthracite D29,5cm

I need to keep only the word "Anthracite" in the second string, because this word is not in the first string

Is it possible to do something like this?

Salman A
  • 262,204
  • 82
  • 430
  • 521
bahamut100
  • 1,795
  • 7
  • 27
  • 38

4 Answers4

1

You could split the string into an array seperated by space, then remove the array with the lowest number of items from the one with the highest number of items, and all you would have left would be the word you need.

EDIT:

$string1 = "Ass. Présentation Chiara D29,5cm"
$array1 = explode(" ",$string1);

$string2 = "Ass. Présentation Chiara Anthracite D29,5cm"
$array2 = explode(" ",$string2);

$difference = array_diff($array2,$array1);
Jim Wolff
  • 5,052
  • 5
  • 34
  • 44
  • 1
    in this case i think you would make some logic that also detected the largest of the arrays and then subtracted the smallest, unless array_diff does that, been a while since i touched php :) – Jim Wolff May 03 '12 at 08:25
1

Perhaps not the best way to go about it, but try using explode and array_diff like so:

$arr1 = explode(' ', $str1);
$arr2 = explode(' ', $str2);
$diff = array_diff($arr2, $arr1);

$diff would be an array of words that are present in $str2 but not in $str1.

Grexis
  • 1,502
  • 12
  • 15
0
$words1 = explode(" ",$str1);
$words2 = explode(" ",$str2);

print_r(array_diff($words1,words2);

http://php.net/manual/en/function.array-diff.php

Andrew Hall
  • 3,058
  • 21
  • 30
  • 1
    This might work if `$str1` is the string containing `Anthracite` and `$str2` is the one without `Anthracite`. – Salman A May 03 '12 at 08:23
0

try this:

<?php

        $keywordString = "Ass. Présentation Chiara D29,5cm";
        $keywordArray  = explode(" ", $keywordString);        

        $string = "Ass. Présentation Chiara Anthracite D29,5cm";
        $stringArray = explode(" ", $string);


        foreach ($keywordArray as $keyword)
                $stringArray = preg_grep("/{$keyword}/i", $stringArray, PREG_GREP_INVERT);

        echo "<pre>";
        print_r($stringArray);
        echo "</pre>";
        exit;
?>
Chintan
  • 1,204
  • 1
  • 8
  • 22