1

I am trying to remove two characters from the end of each line (if they exist) in an array map.

These characters do not always exist

So I am trying to convert

Array ( [0] => C7130A-B [1] => RB2-8120 [2] => RM1-1082-000B [3] => 0950-4768B [4] => C7130B )

to

Array ( [0] => C7130A [1] => RB2-8120 [2] => RM1-1082-000 [3] => 0950-4768 [4] => C7130 )

Basically I am trying to Eliminate B or -B from the end, I have found a way to do this on a string but cannot on an array.

I have tried many options I have found here on Stack and have sadly had no luck.

function cleanit($s) {
    return rtrim($s, "B");
}

$words = strtoupper($words);
$toBeFound = explode(PHP_EOL, $words);
$war = array_map('cleanit', $toBeFound);
echo('Begin<br>');
print_r($war); 
echo('<br>End');

So far the best result I have had is to remove the B (or -B) from the last item in the array. Which is the result of this code.

Array ( [0] => C7130A-B [1] => C7130B [2] => RM1-1082-000B [3] => 0950-4768B [4] => C7130 )
Patrick W
  • 1,485
  • 4
  • 19
  • 27
Jesse
  • 33
  • 3

2 Answers2

0

Here is documentation that provides what you needed.

Code sample:

function cleanit($s) {
  // return rtrim($s, "B");
  $b = strrpos($s,"B");
  $-b = strrpos($s,"-B");

  if($-b > -1) return str_replace($s,"-B");
  if($b > -1) return str_replace($s,"B");
  return $s;
}
Arend
  • 3,741
  • 2
  • 27
  • 37
0

You can use regex with preg_replace like this ($ for remove only on the end of string) :

$myArray = array('C7130A-B', 'RB2-8120', 'RM1-1082-000B', '0950-4768B', 'C7130B');
function cleanit($val)
{
    return preg_replace('/(-B|B)$/','',$val);
}
$resultArray = array_map('cleanit', $myArray);
print_r($resultArray);

Array ( [0] => C7130A [1] => RB2-8120 [2] => RM1-1082-000 [3] => 0950-4768 [4] => C7130 ) 
Florian Richard
  • 80
  • 1
  • 10