Pomoc - Szukaj - Użytkownicy - Kalendarz
Pełna wersja: [PHP]Porównywanie 2 ciągów
Forum PHP.pl > Forum > Przedszkole
Krisu
Przeglądałem funkcje w manualu, jednak nie zauważyłem takiej, która by mi pomogła.

Mam 2 ciągi:

Cytat
Ala ma kota, a kot ma Alę.

Cytat
Ktoś coś ma, a kot ma Alę i miskę.

Czy istnieje jakiś sposób, by porównać te dwa ciągi i zwrócić tylko ich część wspólną, czyli

Cytat
, a kot ma Alę

Bardzo pomogłoby mi jakieś naprowadzenie w jaki sposób to rozwiązać.
blahy
mnie naprowadzila wiki: http://en.wikibooks.org/wiki/Algorithm_imp...ommon_substring
  1. <?php
  2. $str1 = 'Ala ma kota, a kot ma Alę.';
  3. $str2 = 'Ktoś coś ma, a kot ma Alę i miskę.';
  4.  
  5. function strlcs($str1, $str2){
  6. $str1Len = strlen($str1);
  7. $str2Len = strlen($str2);
  8. $ret = array();
  9.  
  10. if($str1Len == 0 || $str2Len == 0)
  11. return $ret; //no similarities
  12.  
  13. $CSL = array(); //Common Sequence Length array
  14. $intLargestSize = 0;
  15.  
  16. //initialize the CSL array to assume there are no similarities
  17. for($i=0; $i<$str1Len; $i++){
  18. $CSL[$i] = array();
  19. for($j=0; $j<$str2Len; $j++){
  20. $CSL[$i][$j] = 0;
  21. }
  22. }
  23.  
  24. for($i=0; $i<$str1Len; $i++){
  25. for($j=0; $j<$str2Len; $j++){
  26. //check every combination of characters
  27. if( $str1[$i] == $str2[$j] ){
  28. //these are the same in both strings
  29. if($i == 0 || $j == 0)
  30. //it's the first character, so it's clearly only 1 character long
  31. $CSL[$i][$j] = 1;
  32. else
  33. //it's one character longer than the string from the previous character
  34. $CSL[$i][$j] = $CSL[$i-1][$j-1] + 1;
  35.  
  36. if( $CSL[$i][$j] > $intLargestSize ){
  37. //remember this as the largest
  38. $intLargestSize = $CSL[$i][$j];
  39. //wipe any previous results
  40. $ret = array();
  41. //and then fall through to remember this new value
  42. }
  43. if( $CSL[$i][$j] == $intLargestSize )
  44. //remember the largest string(s)
  45. $ret[] = substr($str1, $i-$intLargestSize+1, $intLargestSize);
  46. }
  47. //else, $CSL should be set to 0, which it was already initialized to
  48. }
  49. }
  50. //return the list of matches
  51. return $ret;
  52. }
  53. var_dump( strlcs($str1, $str2)); //array(1) { [0]=> string(15) "a, a kot ma Alę" }

moznaby tez napisac prostsza wersje samemu porownujac kolejne znaki
To jest wersja lo-fi głównej zawartości. Aby zobaczyć pełną wersję z większą zawartością, obrazkami i formatowaniem proszę kliknij tutaj.
Invision Power Board © 2001-2025 Invision Power Services, Inc.