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

How to replace characters with php regular expression

藏色散人
Release: 2023-03-02 14:20:02
Original
2903 people have browsed it

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>";
Copy after login

更多相关知识,请访问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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template