Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String Combinations Matching

Tags:

string

php

Suppose a string:

$str = 'a_b_c';

I want match all possible combination with a, b, c with above. For example:

b_a_c, c_a_b, a_c_b..etc will be give true when compare with above $str.

NOTE:

$str may be random. eg: a_b, k_l_m_n etc

like image 863
The System Restart Avatar asked Jan 15 '23 22:01

The System Restart


2 Answers

I would split your string into an array, and then compare it to an array of elements to match on.

$originalList = explode('_', 'a_b_c');
$matchList = array('a', 'b', 'c');
$diff = array_diff($matchList, $originalList);
if (!empty($diff)) {
    // At least one of the elements in $matchList is not in $originalList
}

Beware of duplicate elements and what not, depending on how your data comes in.

Documentation:

  • array_diff()
  • explode()
like image 120
Brad Avatar answered Jan 25 '23 20:01

Brad


There is no builtin way to quickly do this. Your task can be accomplished many different ways which will vary on how general they are. You make no mention of null values or checking the formatting of the string, so something like this might work for your purpose:

function all_combos($str,$vals) {
  $s=explode("_",$str);
  foreach($s as $c) {
    if(!in_array($s,$vals)) return false;
  }
  return true;
}

Call like all_combos("b_c_a",array("a","b","c"));

like image 30
parker.sikand Avatar answered Jan 25 '23 21:01

parker.sikand