Matching String Combinations

Assume the line:

$str = 'a_b_c';

I want to combine all possible combinations with a, b, c above. For instance:

b_a_c , c_a_b , a_c_b .. etc. will give true when compared to above $str .

Note:

$str may be random. e.g. a_b , k_l_m_n , etc.

+4
source share
2 answers

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

 $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 arrives.

Documentation:

+7
source

There is no built-in way to do this quickly. Your task can be accomplished in many different ways, which will differ from how complete they are. You don't mention null values ​​or check string formatting, 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 as all_combos("b_c_a",array("a","b","c"));

+2
source

Source: https://habr.com/ru/post/1448061/


All Articles