skip to Main Content

I need to replace with space if any character start from B01 to B99 letter and L01 to L99 in string. This points needs to take care

  1. Replace all "B01" to "B99" and "L01" to "L99" strings by a space except these 17 characters 1JKFE4P03CDB05071
  2. These character(1JKFE4P03CDB05071) always will be of 17 character with L01 to L99 or B01 to B99 or may be other character in between
  3. These 17 character can be anywhere in the string not mandatory that it’s always in last.
  4. This string is coming dynamic everytime. It’s not static.

But my code replace B05 with space from both strings.

This is my code.

<?php

    $teststr= "STTARB0520122012       HT      2021B0532B        31         01283H3 BU     N   EH    2    B    20000      1JKFE4P03CDB05071";

    $barcodearr = array(
        "B01-B99"=>"",
        "L01-L99"=>"",
        );
        
    foreach($barcodearr as $keycode=>$val)
    {
        
        if(strstr($keycode, '-')) 
        {
           $barexp=explode("-",$keycode);
           $startarr = preg_split("/(,?s+)|((?<=[a-z])(?=d))|((?<=d)(?=[a-z]))/i", $barexp[0]);
           $endarr = preg_split("/(,?s+)|((?<=[a-z])(?=d))|((?<=d)(?=[a-z]))/i", $barexp[1]);
           $startnum=$startarr[1];
           $endnum=$endarr[1];
           $startstring=$startarr[0];

           for($i=$startnum;$i<=$endnum;$i++)
           {
                $doblechar=$i;
                if(strlen($i)!=2){
                    $doblechar='0'.$i;
                }
                
                $findh=$startstring.$doblechar;     
                
                if($startstring=='B'){
                                
                    $space='';
                    for($j=1;$j<=$i;$j++)
                    {
                        $space.='&nbsp;';
                    }
                    $teststr=str_replace($findh,$space,$teststr);
                } 
            }
        }   
            
            
    }   

Output should be

$teststr = "STTAR  20122012       HT      2021 32B        31         01283H3 BU     N   EH    2    B    20000      1JKFE4P03CDB05071";

3

Answers


  1. This code should correctly replace characters ‘B01’ to ‘B99’ and ‘L01’ to ‘L99’ with spaces, excluding the last 17-character segment from the replacement.

    <?php
    $str2 = "STTARB0520122012       HT      2021B0532B        31         01283H3 BU     N   EH    2    B    20000      1JKFE4P03CDB05071";
    
    $barcodearr = array(
        "B01-B99" => "",
        "L01-L99" => "",
    );
    
    // Split the string into segments using a regex pattern
    $segments = preg_split('/(?<=d)(?=[A-Z])|(?<=[A-Z])(?=d)/', $str2);
    
    // Exclude the last 17-character segment from replacement
    $lastSegment = end($segments);
    $segmentsWithoutLast = array_slice($segments, 0, -1);
    
    foreach ($barcodearr as $keycode => $val) {
        if (strpos($keycode, '-') !== false) {
            list($start, $end) = explode("-", $keycode);
            $startChar = substr($start, 0, 1); // Get the first character (B or L)
            $startNum = intval(substr($start, 1));
            $endNum = intval(substr($end, 1));
    
            if ($startChar === 'B' || $startChar === 'L') {
                for ($i = $startNum; $i <= $endNum; $i++) {
                    $find = $startChar . sprintf('%02d', $i); // Ensure 2-digit number
                    $replace = str_repeat(' ', $i);
                    // Replace within the segments except the last one
                    foreach ($segmentsWithoutLast as &$segment) {
                        $segment = str_replace($find, $replace, $segment);
                    }
                }
            }
        }
    }
    
    // Reconstruct the string by joining segments
    $result = implode('', $segmentsWithoutLast) . $lastSegment;
    
    echo $result;
    ?>
    
    Login or Signup to reply.
  2. Use a single call of preg_replace() to make the replacement.

    First, try to match the "protected" 17 character substring — if it is matches, make no replacment and advance the regex engine’s position to the end of that string before looking for more matches.

    Otherwise, match the ranged substring starting with B or L followed by two digits (but not 00).

    Code: (Demo)

    $teststr = preg_replace(
        '/1JKFE4P03CDB05071(*SKIP)(*FAIL)|[BL](?!00)d{2}/',
        ' ',
        $teststr
    );
    

    If your "protected" string is dynamic, then insert the preg-escaped value into your pattern.

    $protected = preg_quote('1JKFE4P03CDB05071', '/');
    $teststr = preg_replace(
        "/{$protected}(*SKIP)(*FAIL)|[BL](?!00)d{2}/",
        ' ',
        $teststr
    );
    
    Login or Signup to reply.
  3. Use preg_replace_callback() to create the replacement strings based on the match.

    <?php
    
    $input = 'STTARB0520122012       HT      2021B0532B        31         01283H3 BU     N   EH    2    B    20000      1JKFE4P03CDB05071';
    
    $output = preg_replace_callback(
        '/b[0-9A-Z]{17}b(*SKIP)(*FAIL)|([BL])(?!00)(d{2})/',
        function ($matches) {
            if ($matches[1] === 'B') {
                $r = '&nbsp;';
            } elseif ($matches[1] === 'L') {
                $r = 'whatever';
            }
    
            return str_repeat($r, $matches[2]);
        },
        $input
    );
    
    var_dump($input, $output);
    

    Outputs:

    string(123) "STTARB0520122012       HT      2021B0532B        31         01283H3 BU     N   EH    2    B    20000      1JKFE4P03CDB05071"
    string(177) "STTAR&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;20122012       HT      2021&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;32B        31         01283H3 BU     N   EH    2    B    20000      1JKFE4P03CDB05071"
    

    Here’s a demo on 3V4L.

    And here’s the regex101.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search