简体   繁体   中英

Simple PHP regex replace

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 , using preg_replace , replace the text so that it puts a
between the first dot and the number?

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

This will add the number and new line.

See demo here. 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;

Output:

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

Explanation:

/               : regex delimiter
    (?<=\.)     : lookbehind, make sure we have a dot before
    (?=\d+\.)   : lookahead, make sure we have digits and a dot after
/               : regex delimiter

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM