Учитывая следующий текст:
1. Place pastry on microwave safe plate.2. Heat on high for 3 seconds.3. Cool briefly before handling.
Я хочу заменить все вхождения точки, за которыми следует число (любое число), за которым следует точка.
Например.
.2. or .15.
и заменить его на
.<BR>number.
Для шаблона preg_replace я сейчас использую:
$pattern = "/^(\.[0-9]\.)/";
$replacement = "";
$text= preg_replace($pattern, $replacement, $text);
Как мне с помощью preg_replace заменить текст, чтобы он
между первой точкой и числом?
Попробуй это. Здесь мы используем preg_replace
,
Поиск:
/\.(\d+)\./
добавленной+
для захвата более чем одной цифры и изменения группы захвата только для цифр.Заменить:
.<BR>$1.
$1
будет содержать цифры, записанные в поисковом выражении.
Попробуйте этот фрагмент кода здесь
<?php
ini_set('display_errors', 1);
$string = "1. Place pastry on microwave safe plate.2. Heat on high for 3 seconds.3. Cool briefly before handling.";
echo preg_replace("/\.(\d+)\./", ".<BR>$1.", $string);
Это добавит номер и новую строку.
Смотрите демо здесь. https://regex101.com/r/ktd7TW/1
$re = '/\.(\d+)\./'; //I use () to capture the number and use it in the replace as $1
$str = '1. Place pastry on microwave safe plate.2. Heat on high for 3 seconds.3. Cool briefly before handling.';
$subst = '.<br>$1.'; // $1 is the number captured in pattern
$result = preg_replace($re, $subst, $str);
echo $result;
$text = '1. Place pastry on microwave safe plate.2. Heat on high for 3 seconds.3. Cool briefly before handling.';
$pattern = "/(?<=\.)(?=\d+\.)/";
$replacement = "<br>";
$text= preg_replace($pattern, $replacement, $text);
echo $text;
Выход:
1. Place pastry on microwave safe plate.<br>2. Heat on high for 3 seconds.<br>3. Cool briefly before handling.
Объяснение:
/ : regex delimiter
(?<=\.) : lookbehind, make sure we have a dot before
(?=\d+\.) : lookahead, make sure we have digits and a dot after
/ : regex delimiter