简单的PHP正则表达式替换

时间:2017-09-13 03:51:06

标签: php preg-replace

给出以下文字:

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替换文本,使其在第一个点和数字之间加上?

3 个答案:

答案 0 :(得分:2)

试试这个。我们在这里使用preg_replace

  

搜索 /\.(\d+)\./添加+以捕获多个数字并更改了仅限数字的捕获组。

     

替换 .<BR>$1. $1将包含搜索表达式中捕获的数字。

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

答案 1 :(得分:1)

这将添加数字和新行。

请在此处查看演示。 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;

答案 2 :(得分:0)

$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