`
baby69yy2000
  • 浏览: 182636 次
  • 性别: Icon_minigender_1
  • 来自: 自己输入城市...
社区版块
存档分类
最新评论

php 正则表达式 preg_replace

阅读更多
练习一:
<?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('&' => '&amp;', '<' => '&lt;', '>' => '&gt', '"' => '&quot;');
echo preg_replace($pattern, '$replacement["$0"]', $txt);
//sss &lt;b&gt &amp;


练习三:
$subjects = array("sss <b> &", "<b>aaa</b>");
$patterns = array('/&/', '/</', '/>/', '/"/');
$replacements = array('&amp;', '&lt;', '&gt;', '&quot;');
$rs_array = preg_replace($patterns, $replacements, $subjects);
print_r($rs_array);

/*
Array
(
    [0] => sss &lt;b&gt; &amp;
    [1] => &lt;b&gt;aaa&lt;/b&gt;
)
*/


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

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics