Tìm kiếm và thay thế một chuỗi theo định dạng tùy biến.
mixed preg_replace ( mixed $pattern , mixed $replacement , mixed $subject [, int $limit = -1 [,int &$count ]] )
Với số.
<?php
$string = 'April 15, 2003';
$pattern = '/(w+) (d+), (d+)/i';
$replacement = '${1}1,$3';
echo preg_replace($pattern, $replacement, $string);
?>
Kết quả: “April1,2003”
Với mảng.
<?php $string = 'The quick brown fox jumped over the lazy dog.'; $patterns = array(); $patterns[0] = '/quick/'; $patterns[1] = '/brown/'; $patterns[2] = '/fox/'; $replacements = array(); $replacements[2] = 'bear'; $replacements[1] = 'black'; $replacements[0] = 'slow'; echo preg_replace($patterns, $replacements, $string); ?>
Kết quả: “The bear black slow jumped over the lazy dog.”
Giá trị cho trước.
<?php
$patterns = array ('/(19|20)(d{2})-(d{1,2})-(d{1,2})/',
'/^s*{(w+)}s*=/');
$replace = array ('3/4/12', '$1 =');
echo preg_replace($patterns, $replace, '{startDate} = 1999-5-27');
?>
kết quả : "$startDate = 5/27/1999"
 
			
49 thoughts on “Hàm Preg_replace php”
Comments are closed.