Home  >  Article  >  Backend Development  >  How to replace characters with php regular expression

How to replace characters with php regular expression

藏色散人
藏色散人Original
2020-07-14 09:13:442847browse

php正则表达式字符串替换字符的方法:首先创建一个PHP示例文件;然后获取需要被替换的字符串;接着使用正则表达式匹配并替换相关字符;最后用echo输出替换后的字符串即可。

How to replace characters with php regular expression

php正则表达式替换匹配的字符串

<?php
 
//正则表达式替换相应字符串的用法
$url = "这是搜索链接:http://www.baidu.com/和http://www.google.com/";  //内容
 
$rule = "(http://)([a-zA-z0-9./-]+)"; //正则表达式 ,()内表示子串
 
$replace = "<a href=\"\\0\">\\0</a>";  //正则表达式,\0表示全部匹配部分
$replace01 = "<a href=\"\\0\">\\1</a>";  //正则表达式,\1表示匹配的第一部分
$replace02 = "<a href=\"\\0\">\\2</a>";  //正则表达式,\2表示匹配的第二部分
 
echo "原始字符串:$url"."<br>";  //输出原始字符串
echo "<hr>";
 
echo "全部匹配部分:".mb_ereg_replace($rule,$replace,$url);
echo "<br>";
echo "<hr>";
 
echo "匹配的第1部分:".mb_ereg_replace($rule,$replace01,$url);
echo "<br>";
echo "<hr>";
 
echo "匹配的底2部分:".mb_ereg_replace($rule,$replace02,$url);
echo "<br>";
echo "<hr>";

更多相关知识,请访问PHP中文网

The above is the detailed content of How to replace characters with php regular expression. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn