Cú pháp:

preg_replace_callback ( string $pattern , callable $callback , string $subject ) : string
  • $pattern: biểu thức chính quy (regex) để tìm chuỗi cần thay.
  • $callback: hàm sẽ được gọi mỗi khi regex tìm thấy kết quả.

    • Callback nhận 1 mảng $matches, trong đó $matches[0] là toàn bộ chuỗi khớp, $matches[1], $matches[2]... là các nhóm con (capturing group).

  • $subject: chuỗi cần xử lý.

Ví dụ cơ bản

Ví dụ 1: Thay số thành số nhân đôi

$text = "Số: 4, 7 và 10";

$result = preg_replace_callback('/\d+/', function($matches) {
    return $matches[0] * 2;
}, $text);

echo $result;
// Kết quả: "Số: 8, 14 và 20"
  • Regex /\d+/ tìm tất cả dãy số.

  • Callback nhận $matches[0] (ví dụ "4") và trả về số nhân đôi.

Ví dụ 2: Viết hoa chữ cái đầu mỗi từ

$text = "hello world, php regex";

$result = preg_replace_callback('/\b[a-z]/', function($matches) {
    return strtoupper($matches[0]);
}, $text);

echo $result;
// Kết quả: "Hello World, Php Regex"

Ví dụ 3: Thay đổi ảnh

$html = '<img src="a.jpg" alt="anh 1"><img src="b.png" alt="anh 2">';

$result = preg_replace_callback('/<img[^>]+>/', function($matches) {
    $img = $matches[0];
    return str_replace('.jpg', '.webp', $img);
}, $html);

echo $result;
// Kết quả: <img src="a.webp" alt="anh 1"><img src="b.png" alt="anh 2">

Một số regex thường dùng

  • \d → chữ số (0-9)

  • \w → ký tự chữ + số + gạch dưới

  • . → bất kỳ ký tự nào (trừ xuống dòng)

  • + → lặp ≥1 lần

  • * → lặp ≥0 lần

  • ? → tùy chọn (0 hoặc 1)

  • (...) → nhóm (capturing group)

  • \b → ranh giới từ (word boundary)

Ứng dụng trong WordPress

Tìm và thay thế đường dẫn hình ảnh trong gallery sử dụng thư viện jetpack gallery wordpress (mình không muốn sử dụng cdn của thư viện )

add_filter('the_content', function ($content) {
    return preg_replace_callback('/<img[^>]+>/', function ($matches) {
        $img = $matches[0];

        // Lấy attachment ID từ data-id
        if (preg_match('/data-id="(\d+)"/', $img, $idMatch)) {
            $attachment_id = (int) $idMatch[1];

            // Lấy URL chuẩn từ WP
            $new_src = wp_get_attachment_image_url($attachment_id, 'full');

            if ($new_src) {
                // Xóa decoding và srcset
                $img = preg_replace('/\sdecoding="[^"]*"/', '', $img);
                $img = preg_replace('/\ssrcset="[^"]*"/', '', $img);

                // Thay src = URL từ wp_get_attachment_image_url
                $img = preg_replace('/\ssrc="[^"]*"/', ' src="' . esc_url($new_src) . '"', $img);
            }
        }

        return $img;
    }, $content);
});

 

 

Bài viết liên quan

post-no-image

Trang website có nhiều hiệu ứng hay đẹp tham khảo

post-no-image

Chia nhỏ task cron tự động

post-no-image

Sửa lỗi phân trang khi custom query trong WP Query

post-no-image

Hướng dẫn chuyển ảnh về định dạng Webp hay AVIF

post-no-image

Xử lý change status order Woocommerce khi refund từ Paypal

post-no-image

Hướng dẫn build lại ảnh hoặc media tải lên trong WordPress