Search code examples
phpregexpreg-replacesentence

Inject <br> between numbered sentences ending in a dot, but not after dots preceded by a number


Given the following text:

1. Place pastry on microwave safe plate.2. Heat on high for 3 seconds.3. Cool briefly before handling.

I am wanting to replace all occurrences of a dot followed by a number (any number) followed by a dot.

Eg.

.2. or .15.

and replace it with

.<BR>number.

For the preg_replace() pattern, I am currently using:

$pattern = "/^(\.[0-9]\.)/";
$replacement = "";
$text=  preg_replace($pattern, $replacement, $text);

How do I use preg_replace() to replace the text so that it puts a <BR> between the first dot and the number?


Solution

  • Try this one. Here we are using preg_replace.

    Search: /\.(\d+)\./ Added + for capturing more than one digit and changed capturing group for only digits.

    Replace: .<BR>$1. $1 will contain digits captured in search expression.

    Try this code snippet here

    <?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);