K.K
K.K

Reputation: 11

matching dissimilar strings in php

heres the situation i have an entry in my database where the field values are like given below

and in the frontend i get a string something like 64|65|72|0|0|0|0| (please see the entry is similar to the 1 field but rearranged). based on options entered by the user(please note the string length will remain the same).

is it possible to equate the user field with the database field so as to get the data from the database for the matched field

Upvotes: 1

Views: 84

Answers (5)

Guile
Guile

Reputation: 1494

I would say like others : Split your string into array, then compare it

$myInput = explode('|', $strInput);
$similar = (true === empty(array_diff($myInput, $data))
        && true === empty(array_diff($data, $myInput)));

Correction (empty only accepts variables)

$myInput = explode('|', $strInput);
$diff1 = array_diff($myInput, $data);
$diff2 = array_diff($data, $myInput);
$similar = (true === empty($diff1)
        && true === empty($diff2));

Upvotes: 0

anubhava
anubhava

Reputation: 784918

Split the input and database string by pipe and sort them before comparing resulting arrays like this:

$arr1 = explode('|', '64|65|0|0|72|0|0|');
$arr2 = explode('|', '64|65|72|0|0|0|0|');
sort($arr1);
sort($arr2);
if ($arr1 === $arr2)
   echo "Matched\n";
else
   echo "Not Matched\n";

Upvotes: 0

Zach Rattner
Zach Rattner

Reputation: 21323

I'm not exactly sure what the re-ordering rules are, but let's illustrate the solution with the form ABCDEFG -> ABDECFG.

You can either re-order the data in Javascript before sending it back to the server, or re-order on the server before sending the data to MySQL. Since your question is filed under PHP/MySQL, I'm assuming you'd like to perform the latter.

Please note that this is not the most elegant solution, but it does illustrate the approach clearly. You can polish it once you understand the underlying idea:

// Assume $Unsorted = '64|65|0|0|72|0|0|'
$Segments = explode('|', $Unsorted);
if (count($Segments) != 7)  
{
    // Handle the error case
}

$Sorted = sprintf
(
    '%u|%u|%u|%u|%u|%u|%u|',
    $Unsorted[0],
    $Unsorted[1],
    $Unsorted[3],
    $Unsorted[4],
    $Unsorted[2],
    $Unsorted[5],
    $Unsorted[6]
);

// Now, $Sorted = '64|65|0|0|72|0|0|'

Upvotes: 0

Pete
Pete

Reputation: 1299

If you explode the string you'll have an array that you can sort.

But that's no use unless the data in the database is also sorted.

e.g. $my_array = explode("|", trim($str, "|") );

Upvotes: 2

Travesty3
Travesty3

Reputation: 14469

function rearrange($string)
{
    $temp = explode("|", $string);
    // $temp is now an array. sort it however you want and store it back in $temp
    return implode("|", $temp);
}

Upvotes: 0

Related Questions