进阶 - 替换

  • 作者:KK

  • 发表日期:2017.7.24


需求

有字符串<img src="img/1.jpg"><img src="img/3.jpg">

需要在src里加上域名,变成类似http://xxx.com/img/1.jpg这样


JS代码

var str = '<img src="img/1.jpg"><img src="img/3.jpg">';
var pattern = /src="(.+?)"/g;

str = str.replace(pattern, 'src="http://xxx.com/$1"');
console.log(str);
//<img src="http://xxx.com/img/1.jpg"><img src="http://xxx.com/img/3.jpg">

讲解

  1. 先要找到要替换的目标,这个按以前的逻辑,直接定义正则表达式来匹配替换目标

  2. 可是替换目标中要用括号定义替换的部分,因为并非全部都要替换,比如上例中src=这块是不用替换的

  3. 执行替换方法,各编程语言的替换手段不同,JS可以直接用字符串的replace方法传入正则来查找替换的内容,然后在第2个参数里用$1表示pattern第1个括号里匹配的内容,但换着PHP就不能用str_replace函数了,有专用的preg_replace函数,下面有PHP代码示例


PHP代码

$str = '<img src="img/1.jpg"><img src="img/3.jpg">';
$pattern = '#src="(.+?)"#';

$str = preg_replace($pattern, 'src="http://xxx.com/$1"', $str);
echo $str;
//<img src="http://xxx.com/img/1.jpg"><img src="http://xxx.com/img/3.jpg">

替换更多个

道理很简单,在表达式里加多几对括号,替换成的字符串里顺应地增加$2$3这些就行了

var str = '<a href="/path/1.html">新闻1</a>  <a href="/path/2.html">新闻2</a>';
var pattern = /<a href="(.+?)">(.+?)<\/a>/g;

str = str.replace(pattern, '<a href="http://xxx.com$1">重磅:$2<\/a>');
console.log(str);
//<a href="http://xxx.com/path/1.html">重磅:新闻1</a>  <a href="http://xxx.com/path/2.html">重磅:新闻2</a>

那PHP的就不废话了,逻辑正常的人都能理解到嘛