2017-09-13 58 views
0

鑑於以下文字:簡單的PHP正則表達式替換

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,替換文本,以便它把一個
之間的第一個點和數字?

+1

刪除''^和再試一次'「/\.[0-9]+ \ ./「' –

回答

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 –

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