练习一:
练习二:
练习三:
preg_replace_callback函数
<?php
$txt = "This is a link to http://www.google.com/";
$pattern1 = '/http:\/\/(.*)\//';
$pattern2 = '/http:\/\/(.*)\//e';
$replacement1 = "<a href='$0'>$1</a>";
$replacement2 = 'strtoupper("<a href=\'$0\'>$1</a>")';
echo preg_replace($pattern1, $replacement1, $txt);
//This is a link to <a href='http://www.google.com/'>www.google.com</a>
echo "<br />";
echo preg_replace($pattern2, $replacement2, $txt);
//This is a link to <A HREF='HTTP://WWW.GOOGLE.COM/'>WWW.GOOGLE.COM</A>
?>
练习二:
$txt = "sss <b> &";
$pattern = '/[&<">]/e';
$replacement = array('&' => '&', '<' => '<', '>' => '>', '"' => '"');
echo preg_replace($pattern, '$replacement["$0"]', $txt);
//sss <b> &
练习三:
$subjects = array("sss <b> &", "<b>aaa</b>");
$patterns = array('/&/', '/</', '/>/', '/"/');
$replacements = array('&', '<', '>', '"');
$rs_array = preg_replace($patterns, $replacements, $subjects);
print_r($rs_array);
/*
Array
(
[0] => sss <b> &
[1] => <b>aaa</b>
)
*/
preg_replace_callback函数
<?php
$txt = "vim --- vim -";
$pattern = '/\bvim\b/';
function fn_callback($matches) {
return "<b>" . $matches[0] . "</b>";
}
$rs = preg_replace_callback($pattern, "fn_callback", $txt);
echo $rs;
//<b>vim</b> --- <b>vim</b> -
?>