Search code examples
phpstringexplodetrim

Exploding and Trimming Strings In PHP


i have format of string like this:

1PR009427S0000754

first let me explain this format. if you see the "1P" that means its the start of the part number of a product. Starting from the "S" that represents the serial number of the product. with this format of strings i am able to split or explode that one string into two without any problem, not until i encounter these kind of string formats.

1P0005-00118-33S3S216

1PS-35C-602S6510873143

1P0005-00115-SPS3S216

if you guys noticed that for these new formats they got a couple of "S" in one string the problem is when I'm Exploding the string i used the 1P to tell the program that it is the start of the part number and as soon as it sees the "S" that's the start of the serial number of the product. My concern is, when I'm exploding the new strings I'm getting a result of a wrong part number and serial number because of a couple of S that appears in the strings.

here is the sample of my program

if($_POST['submit'])
{
    $text = explode("<br />",nl2br($_POST['pn']));
    foreach ($text as $key => $value)
    { //start foreach statements
        $precage = "0617V";
        $presym = "[)>";
        $partn = "1P";
        $serial = "S";

        $match = preg_match('/[)>0617V1PS]/', $value);
        if($match == true)
        {      

            $value2 = substr($value[1], 5);

            $result = explode("1P", $value2);
            $fin_pnresult = explode("S", $result[1]) ; 

            $serial1 = strrchr($value2, $serial);
            $fin_serial = substr($serial1, 1);
            $cageresult = substr($value2, 0, strpos($value2, "1P"));


        }
    }

?>

Thank you guys for your help.


Solution

  • i would suggest you change the delimiters if you have any control over that part.

    here's a quick and dirty approach to your current issue.

    $string = "1P0005-00118-33S3S2161PS-35C-602S65108731431P0005-00115-SPS3S216";
    
    $products = explode("1P", $string);
    
    foreach ($products as $product) {
      if (strlen($product) == 0) continue;
    
      $first_s = strpos($product, "S", 1);
      if (substr($product, $first_s, 2) == 'SP') {
        $first_s = strpos($product, "S", $first_s+1);
      }
      $serial = substr($product, $first_s+1, strlen($product));
      $product_id = substr($product, 0, $first_s);
      echo $product_id."\n".$serial."\n\n";
    }
    // should give you
    /*
    0005-00118-33
    3S216
    
    S-35C-602
    6510873143
    
    0005-00115-SP
    3S216
    
    */