Truncate strings in an array which match a particular format, then filter out unaltered elements

Viewed 78

I have an array which is a mix of strings that I want to keep and strings that I don't want to keep. Of the strings to keep, I need to truncate them from their first occurring slash.

My array:

$code = [
    'PO/2022/0001',  // modify
    'abc',           // remove
    'xyz',           // remove
    'PO2022/0001',   // remove
    'XY/2022/0002',  // modify
    'PO/2022/0232'   // modify
];

I am trying to explode the strings in the above array on / and if the newly generated array has 3 elements, then I need to push the first value into my result array.

Expected result from sample input:

['PO', 'XY', 'PO']

Can I know what is the better and efficient approach to do this?

This is what I have so far:

foreach ($code as $v) {
    $nwCode = explode("/",$v);
    if(count($nwCode) == 3) {
      $nwAry[] = $newCode[0];
    }
    
    $nwCode = [];
}

echo '<pre>',print_r ($nwAry).'</pre>';
2 Answers
$code = ['PO/2022/0001', 'abc','xyz','PO2022/0001', 'XY/2022/0002','PO/2022/0232'];

$prefixes = array_map(function($e){
  $nwCode = explode('/', $e);
  if(count($nwCode) == 3)
  {
    return $nwCode[0];
  }
} ,$code);

$prefixes = array_filter($prefixes, function($e){ if(strlen($e) > 0) return true; });

echo "<pre>";
var_dump($prefixes);
echo "</pre>";

The array_map used to get those prefixes, while array_filter to remove the empty prefixes from the unmatching items.

You could use array_reduce too.

$prefixes = array_reduce($code, function($carry, $item){
  $nwCode = explode('/', $item);
  if(count($nwCode) == 3)
  {
    array_push($carry, $nwCode[0]);
  }
  return $carry;
}, array());

Because you want to perform replacements on strings with a strict format/signature AND filter out elements that do not match the signature, the best tool that PHP has to offer is preg_filter().

Pattern breakdown:

^              #start of string
[^/]+          #one or more non-slash characters
\K             #forget/release previously matched characters
(?:/[^/]+){2}  #match 2 sets of slash followed by one or more non-slash characters
$              #end of string

Code: (Demo)

var_export(
    preg_filter(
        '~^[^/]+\K(?:/[^/]+){2}$~',
        '',
        $code
    )
);

Output:

array (
  0 => 'PO',
  4 => 'XY',
  5 => 'PO',
)

IF you require indexed keys, call array_values() on the result array.

Related