PHP:preg_replace

关于preg_match: http://www.cnblogs.com/helww/p/3466720.html

关于preg_match_all:暂时没有完整的

preg_replace_callback核心例子1:把<a>标签的文本中的<替换为空,文本的其它部分不变

$note = '<a href="http://www.so.com"><>ab<></a><a href="http://www.so.com"><>ab<></a>';
function filter_subject($matches){
   return $matches[1].(str_replace(array("<", ">"), array(" ", " "), $matches[2])) . $matches[3];
}
$note = preg_replace_callback('/(<a href.*?>)(.*?)(</a>)/', "filter_subject", $note);

输出:"<a href="http://www.so.com">  ab  </a><a href="http://www.so.com">  ab  </a>"

preg_replace: 能够将匹配的模式处理成目标模式。

任务:把[img]100[/img]处理为<img>100</img>

代码:

<?php
$str = '[img]100[/img]test.png[img]1000[/img]';
$newstr = preg_replace('/[img](.*?)[/img]/', '<img>$1</img>', $str);
var_dump($newstr);

输出:

string(37) "<img>100</img>test.png<img>1000</img>"

关于括号的用法,看下最后两个任务:http://www.cnblogs.com/helww/p/3466720.html

代码2:

<?php
$str = '[img]100[/img]test.png[img]1000[/img]';
$newstr = preg_replace('/[img](.*?)[/img]/', '<img>1</img>', $str);
var_dump($newstr);

代码3:

<?php
$str = '[img]100[/img]test.png[img]1000[/img]';
$newstr = preg_replace('/[img](.*?)[/img]/', "<img>\1</img>", $str);
var_dump($newstr);

代码4:

<?php
$str = '[img]100[/img]test.png[img]1000[/img]';
$newstr = preg_replace('/[img](.*?)[/img]/e', "parse_image($1)", $str);
var_dump($newstr);
function parse_image($str)
{
    return '<img>'.$str.'</img>';
}

代码5:

<?php
$str = '[img]100[/img]test.png[img]1000[/img]';
$newstr = preg_replace('/[img](.*?)[/img]/', parse_image('$1'), $str);
var_dump($newstr);
function parse_image($str)
{
    return '<img>'.$str.'</img>';
}

代码6:

<?php
$str = '[img]100[/img]test.png[img]1000[/img]';
$newstr = preg_replace('/[img](.*?)[/img]/', parse_image("$1"), $str);
var_dump($newstr);
function parse_image($str)
{
    return '<img>'.$str.'</img>';
}

实验:转换以下字符串

[img]http://xss.re/a.php[/img]aaa[img]http://xss.re/a.php[/img]

转换规则是:[img]*[/img]两个标签内的链接,如果是在.360.cn域,则信任,否则过滤url

上述的字符串转换后为:[img][/img]aaa[img][/img]

实现代码:

原文地址:https://www.cnblogs.com/helww/p/3699864.html