user1414880
user1414880

Reputation:

multiple find and replace in php

I have a string like the one below

$str="<444970836741>BOA LTD.                                              
  CR
      9,00,000.00         Not Available           Not Available    Not Available           Not Available    TBI   31/12/13    31/12/13"; 

and I need the output as below

444970836741,900000.00,31/12/13,31/12/13

I need to do the following

  1. Remove '<' and '>'
  2. Remove TBI
  3. Remove 'Not Available' field
  4. preserve sn (i.e 444970836741)
  5. preserve amount but remove comma from amount(900000.00)
  6. preserve start date and end date (both 31/12/13) 6.

I tried with str_replace but it is really painful to remove all whitespaces and unnecessary characters. Can it be done in PHP?

Upvotes: 0

Views: 459

Answers (2)

W Kristianto
W Kristianto

Reputation: 9303

strcspn, preg_replace and str_replace can help you

$str = "<444970836741>BOA LTD.                                              
  CR
      9,00,000.00         Not Available           Not Available    Not Available           Not Available    TBI   31/12/13    31/12/13"; 

function complicated($string)
{
    // Change into array
    $array = explode(" ", $string);

    // Unset element has no numbers
    foreach ($array as $key => $value)
    {
        if(strcspn($value, '0123456789') == strlen($value)){
            unset($array[$key]);
        }
    }

    // Return all the values of an array
    $array = array_values($array);

    // Remove everything from a string but just numbers
    $array[0] = preg_replace("/[^0-9]/","",$array[0]);

    // Remove commas
    $array[1] = str_replace(',', '', $array[1]);

    // Return
    return implode(',', $array);
}

echo complicated($str);

Upvotes: 1

Dmitriy.Net
Dmitriy.Net

Reputation: 1500

Use str_replace with array condition. See "$search" description for this function:

The value being searched for, otherwise known as the needle. An array may be used to designate multiple needles.

$str = str_replace(array('<', '>', 'TBI', 'Not Available', ','), '', $str);

And, for remove all double whitespaces, use preg_replace

$str = preg_replace('/\s+/', ' ', $str);

Upvotes: 0

Related Questions