Заменить поврежденную буквенно-цифровую подстроку идентификатора, содержащую нежелательные пробелы

У меня есть динамический контент, но некоторые символы из строки отсутствуют. Я хочу заменить эти символы, чтобы сделать это правильно. У меня есть полный идентификатор заказа, но в его содержании есть пробел.

  1. Мне нужно заменить идентификатор заказа, в котором есть пробел, на правильный идентификатор заказа.
  2. У меня правильный идентификатор заказа

Это пример содержимого:

$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.";

Мой код:

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

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

echo $content;

Выходной контент должен быть

$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.";

🤔 А знаете ли вы, что...
PHP является интерпретируемым языком программирования.


1
89
2

Ответы:

function correctString(string $content): false|string {

  $len = 18;       // The length of the id
  $minLen1 = 12;   // The minimum length of the first part of the malformed id
  $minLen2 = 3;    // The minimum length of the second part of the malformed id
                   // Of course minLen1 + minLen2 should be smaller than $len

  preg_match_all("/[A-Z0-9]{{$len}}/", $content, $matches);

  if (count($matches[0]) === 2 && $matches[0][0] === $matches[0][1]) {

    // Found valid id, and also the second, and it they are identical
    return $content;

  } elseif (count($matches[0]) === 1) {

    // Found valid id, but not the second one
    $part1 = substr($matches[0][0], 0, $minLen1);
    $part2 = substr($matches[0][0], $len - $minLen2, $minLen2);
    preg_match_all("/$part1 $part2/", $content, $matches2);

    if (count($matches2[0]) === 1) {

      // Found second, but malformed id
      return str_replace($matches2[0][0], $matches[0][0], $content);
      
    } else {

      // Found no second malformed id
      return false;

    }

  } else {

    // Found no id at all
    return false;

  }

}

echo correctString('Order ... is JKSZ089P6X07A07012.Order is ... id JKSZ089P6X07 012') .  "\n";
echo correctString('Order ... is JKSZ089P6X07A07012.Order is ... id JKSZ089P6X07A07012') .  "\n";
echo correctString('Order ... is JKSZ089P6X07A0701.Order is ... id JKSZ089P6X07 012') .  "\n";

Выход:

  Order ... is JKSZ089P6X07A07012.Order is ... id JKSZ089P6X07A07012
  Order ... is JKSZ089P6X07A07012.Order is ... id JKSZ089P6X07A07012
                      <- Echoing false prints as an empty line 

Решено

Ваш набор образцов входных данных показывает, что проблема с пробелами постоянно возникает после 12 символов.

Чтобы восстановить строку с помощью $orderId, создайте шаблон регулярного выражения, который заменяет 3 символа после 12-го символа «выражением с одним или несколькими пробелами». Я заключаю шаблон в границы слов, чтобы исключить вероятность ложноположительных замен (искажение непреднамеренных подстрок). Если совпадение есть, замените его известным значением $orderId.

Код: (Демо)

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

var_export(preg_replace($regex, $orderId, $content));

Если на самом деле заменяемые пробелы — это &nbsp;, то вот модификация моего приведенного выше шаблона регулярного выражения. (Демо)

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