phpstringreplacepreg-replacecorrupt-data

Replace corrupted alphanumeric id substring containing unwanted spaces


I have content that is coming dynamic but some characters from string are missing. I want to replace that characters to make it correct. I have complete order id but in content it's coming with space.

  1. I need to replace order id that is coming with space with correct order id.
  2. I have correct order id

This is example content:

$content = "Order is purchased on 23-05-2023.Order is in progress&nbsp and you can see order status on website by enter id JKSZ089P6X07   012";

$content = "Order Model is Ford and year model 2017.Order id is 6FTYF75C7HD  715 and Vehicle type is commercial.";                     

$content = "Order Model is Mahindra and year model 2015.Order id is 9PKKJ7FS3CD  890 and Vehicle type is personal.";

My code:

$orderId = "JKSZ089P6X07A07012";
$getChar =  substr(orderId ,0,12);

if(strpos( $content, $getChar ) !== false ) { 
    echo "found";
    $content = str_replace($getChar," ",$content);
}

echo $content;

Output content should be

$content = "Order is purchased on 23-05-2023.Order is in progress and you can see order status on website by enter id JKSZ089P6X07A07012";

$content = "Order Model is Ford and year model 2017.Order id is 6FTYF75C7HD680715 and Vehicle type is commercial.";                   

$content = "Order Model is Mahindra and year model 2015.Order id is 9PKKJ7FS3CD347890 and Vehicle type is personal.";

Solution

  • Your set of sample input data indicates that your whitespace problem consistently occurs after the 12 character.

    To repair the string using the $orderId, create a regex pattern that replaces the 3 characters after the 12th character with a "one-or-more whitespace expression". I am wrapping the pattern in word boundaries to eliminate the chance of making false-positive replacements (mangling unintended substrings). If there is a match, replace it with your known $orderId value.

    Code: (Demo)

    $regex = '#\b' . substr_replace($orderId, '\s+', 12, 3) . '\b#';
    
    var_export(preg_replace($regex, $orderId, $content));
    

    If the spaces to be replaced are actually  , then here is the modification of my above regex pattern. (Demo)

    $regex = '#\b' . substr_replace($orderId, '(?: )+', 12, 3) . '\b#';