php 正则表达式 preg_replace

本文通过几个具体的PHP正则表达式示例介绍了如何进行URL转换、特殊字符转义及文本格式化等操作。首先展示了如何将普通文本中的URL转换为超链接,接着解释了如何在字符串中正确处理HTML特殊字符,最后演示了批量处理字符串数组的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

练习一:

<?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('&' => '&', '<' => '<', '>' => '&gt', '"' => '"');
echo preg_replace($pattern, '$replacement["$0"]', $txt);
//sss <b&gt &


练习三:

$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> -
?>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值