Hướng dẫn dùng back reference trong PHP

Cú pháp hàm preg_replace()

Hàm preg_replace sử dụng RegExp (xem cách viết biểu thức chính quy RegExp) để tìm kiếm và thay thế chuỗi.

Nội dung chính

  • Cú pháp hàm preg_replace()
  • Ví dụ 1 về preg_replace
  • Ví dụ 2 $replacement đặc biệt
  • Ví dụ 3 dùng preg_replace với mảng xử lý BBCODE
  • Not the answer you're looking for? Browse other questions tagged php regex escaping backreference or ask your own question.

preg_replace($pattern, $replacement,$subject)

Hàm này tìm trong $subject các chuỗi con phù hợp với mẫu $pattern là một biểu thức RegExp, thay thế chuỗi tìm thấy bởi $replacement

  • $pattern : Biểu thức RegExp để tìm kiếm có thể là một chuỗi hoặc một mảng.
  • $subject : Chuỗi nhập vào để tìm kiếm
  • $replacement : Giá trị thay thế, có thể là chuỗi hoặc mảng. Nếu $pattern là mảng $replacement là chuỗi thì mọi kết quả tìm kiểm theo $pattern được thay thể bởi $replacement. Nếu cả $pattern, $replacement là mảng thì nó thay thế theo phần tử tương ứng.

$replacement đặc biệt có thể được biểu diễn một cách đặc biệt, nó có thể chứa các tham chiếu dùng để chèn nội dung, tham chiếu có dạng $n với n = 0 - 99. Với $0 tương ứng với sự phù hợp với toàn bộ $pattern, $1, $2 ... tương ứng với mẫu con theo thứ tự trong $pattern (Xem ví dụ 2)

Hàm preg_replace trả về chuỗi hoặc mảng các chuỗi để tìm kiếm và thay thế.

Ví dụ 1 về preg_replace

Dùng biểu thức chính quy và hàm preg_replace tìm các cụm số thay thế bằng 2000


//OUT:
Ví dụ về hàm preg_replace 2000 2000

Ví dụ 2 $replacement đặc biệt

Ví dụ sau, cho chuỗi có nội dung: 'Tháng ... Năm ....' đảo thành 'Năm ..., Tháng ...'


//OUT:Năm 2017, Tháng 12

Với ví dụ trên về $pattern cờ ui cho biết không phân biệt chữ hoa, chữ thường và dùng chuỗi Unicode. Với mẫu này trong nó có các $pattern con là (\w+) tương ứng với $1, (\d+) tương ứng với $2 ...Và $replacement sử dụng các chỉ số này để tạo chuỗi thay thế.

Ví dụ 3 dùng preg_replace với mảng xử lý BBCODE

Ví dụ sau sẽ chuyển các mã bbcode: b, i, u, img, url thành mã HTML thông thường.

$1',
        '$1',
        '$1',
        '',
        '$1',
        '$2'
    );

    $str = preg_replace ($search, $replace, $str);
    return $str;
}
//Test
$bbcdoe = '[url=https://xuanthulab.net][b]xuanthulab.net[/b][/url]';
echo bbcode2Html($bbcdoe);
//OUT HTML: xuanthulab.net

Situation

I want to use preg_replace() to add a digit '8' after each of [aeiou].

Example

from

abcdefghij

to

a8bcde8fghi8j


Question

How should I write the replacement string?

// input string
$in = 'abcdefghij';

// this obviously won't work ----------↓
$out = preg_replace( '/([aeiou])/', '\18',  $in);

This is just an example, so suggesting str_replace() is not a valid answer.
I want to know how to have number after backreference in the replacement string.

asked Aug 2, 2013 at 23:54

MightyPorkMightyPork

17.6k10 gold badges73 silver badges128 bronze badges

The solution is to wrap the backreference in ${}.

$out = preg_replace( '/([aeiou])/', '${1}8',  $in);

which will output a8bcde8fghi8j

See the manual on this special case with backreferences.

answered Aug 2, 2013 at 23:59

4

You can do this:

$out = preg_replace('/([aeiou])/', '${1}' . '8', $in);

Here is a relevant quote from the docs regarding backreference:

When working with a replacement pattern where a backreference is immediately followed by another number (i.e.: placing a literal number immediately after a matched pattern), you cannot use the familiar \1 notation for your backreference. \11, for example, would confuse preg_replace() since it does not know whether you want the \1 backreference followed by a literal 1, or the \11 backreference followed by nothing. In this case the solution is to use \${1}1. This creates an isolated $1 backreference, leaving the 1 as a literal.

answered Aug 3, 2013 at 0:00

jh314jh314

26.2k15 gold badges61 silver badges81 bronze badges

Not the answer you're looking for? Browse other questions tagged php regex escaping backreference or ask your own question.