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
- Replace all "B01" to "B99" and "L01" to "L99" strings by a space except these 17 characters 1JKFE4P03CDB05071
- These character(1JKFE4P03CDB05071) always will be of 17 character with L01 to L99 or B01 to B99 or may be other character in between
- These 17 character can be anywhere in the string not mandatory that it’s always in last.
- 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.=' ';
}
$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
This code should correctly replace characters ‘B01’ to ‘B99’ and ‘L01’ to ‘L99’ with spaces, excluding the last 17-character segment from the replacement.
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)
If your "protected" string is dynamic, then insert the preg-escaped value into your pattern.
Use
preg_replace_callback()
to create the replacement strings based on the match.Outputs:
Here’s a demo on 3V4L.
And here’s the regex101.