请问如何将preg_preg replacee_callback函数改写成preg_preg replacee,函数如下

此页面有帮助到您吗?
您对此内容的反馈非常重要。请告诉我们您的想法。
更多反馈?
我们非常感谢您的反馈。
全局正则表达式匹配通过正则表达式分割字符串
版权所有 (C)快速业务通道
++++选择通道++++
国内服务器厦门电信服务器汕头电信服务器温州电信服务器厦门网通服务器汕头双线服务器美国服务器欧洲服务器美国KT机房服务器美国FDC机房服务器香港服务器新加坡服务器韩国服务器台湾服务器英国服务器德国服务器新加坡Qala机房服务器香港机房服务器法国服务器江苏电信服务器美国TB机房服务器日本服务器河北网通服务器厦门软二服务器台湾机房服务器韩国机房服务器美国ST机房服务器江西电信服务器其他机房服务器菲律宾服务器日本机房服务器菲律宾机房服务器
国内大带宽
欢迎光临凌众科技,我们将竭诚为您提供最优质的服务!业务电话: 技术支持电话:
PHP教程:preg_replace_callback()函数
最近碰到一个问题,要在一段HTML代码的链接中加一个参数,比如其中由一个A标签是这样的:
&a href=&/aaa.php&&链接文字&/a&
我就要在 aaa.php 的后面加上一个参数使其变成 aaa.php?request=xxx ,但问题是不是所有的链接都是aaa.php这样的形式,可能后面已经有了别的参数,比如 aaa.php?id=111 ,这样加的时候就需要把链接变成 aaa.php?id=111&request=xxx 。
由于要处理的是一大块HTML,所以首先想到的解决方案是正则替换,不过 preg_replace 不能做条件判断,只能做一种替换,然后我就找到了 preg_replace_callback() 这个函数,大喜,以为找到了银弹。这个东西的用法和 preg_replace() 函数几乎一样,不过它提供了一个 callback 函数,可以在替换的时候根据条件替换。在PHP手册中提供了这么一个例子:
// 此文本是用于 2002 年的,
// 现在想使其能用于 2003 年
$text = &April fools day is 04/01/2002\n&;
$text.= &Last christmas was 12/24/2001\n&;
// 回调函数
function next_year($matches) {
// 通常:$matches[0] 是完整的匹配项
// $matches[1] 是第一个括号中的子模式的匹配项
// 以此类推
return $matches[1].($matches[2]+1);
echo preg_replace_callback(
&|(\d{2}/\d{2}/)(\d{4})|&,
&next_year&,
// 结果为:
// April fools day is 04/01/2003
// Last christmas was 12/24/2002
看了这个例子之后我以为只要把想要替换的内容替换掉就OK了,比如我只想更改捕获的第二个匹配项,只需要把 $matches[2]中的内容改一下返回就行了。然后我就写了下面的代码测试:
$content = ''&a href=&/aaa.php&&链接1&/a&&a href=&/aaa.php?id=111&&链接2&/a&'';
$content = preg_replace_callback(''/href=[\''|&](.*?)[\''|&]/'', ''add_request'', $content);
// 下面是 add_request 函数定义
function add_source($matches)
if(strpos($matches[1], ''?''))
return $matches[1].''&request=xxx'';
return $matches[1].''?request=xxx'';
凌众科技专业提供服务器租用、服务器托管、企业邮局、虚拟主机等服务,公司网站:
为了给广大客户了解更多的技术信息,本技术文章收集来源于网络,凌众科技尊重文章作者的版权,如果有涉及你的版权有必要删除你的文章,请和我们联系。以上信息与文章正文是不可分割的一部分,如果您要转载本文章,请保留以上信息,谢谢!
你可能对下面的文章感兴趣
上一篇: 下一篇:
Copyright &
厦门优通互联科技开发有限公司 All rights reserved
地址(ADD):厦门软件园二期望海路63号701E(东南融通旁)
邮编(ZIP):361008
传真: 咨询信箱: 咨询OICQ:
《中华人民共和国增值电信业务经营许可证》闽B2-& ICP备案:查看: 49|回复: 8
正则函数preg_replace_callback问题点
TA的每日心情开心昨天&08:33签到天数: 21 天[LV.4]偶尔看看III
正则函数preg_replace_callback,我通过编写一个类来调用函数,在类里面的函数我直接return&&11,得到了直接想要的结果(如图1),可是为什么当我在类里面再次执行一个preg_replace函数时,就得不到了呢?(如图2),麻烦哪位前辈帮忙看一下,谢谢~~~~~
111.png (55.75 KB, 下载次数: 0)
09:05 上传
2222.png (54.28 KB, 下载次数: 0)
09:12 上传
TA的每日心情开心昨天&08:33签到天数: 21 天[LV.4]偶尔看看III
我想通过示例2得到的最终结果应该是&Superyang亮&,可是不知道为什么得不到?
TA的每日心情奋斗昨天&10:17签到天数: 192 天[LV.7]常住居民III
因为你使用了var_dump,上面的数组是var_dump打印的,但是var_dump是没有返回值的,所以return的东西也就没有,所以打印不出来
TA的每日心情开心昨天&08:33签到天数: 21 天[LV.4]偶尔看看III
谢谢哈& & 可是还是不懂耶& &&&你可以说说怎么改吗?
TA的每日心情奋斗昨天&10:17签到天数: 192 天[LV.7]常住居民III
谢谢哈& & 可是还是不懂耶& &&&你可以说说怎么改吗?
你想要什么效果呢,返回替换后的结果么?如果是的话,直接把$str1返回就行了
TA的每日心情开心昨天&08:33签到天数: 21 天[LV.4]偶尔看看III
你想要什么效果呢,返回替换后的结果么?如果是的话,直接把$str1返回就行了
我想得到最后的结果是&Superyang亮&
TA的每日心情奋斗昨天&10:17签到天数: 192 天[LV.7]常住居民III
我想得到最后的结果是&Superyang亮&
直接返回$str1得到的就是你想要的结果啊
TA的每日心情开心昨天&08:33签到天数: 21 天[LV.4]偶尔看看III
发表于 7&天前
直接返回$str1得到的就是你想要的结果啊
我试了的啊& & 还是不对
TA的每日心情奋斗昨天&10:17签到天数: 192 天[LV.7]常住居民III
发表于 7&天前
我试了的啊& & 还是不对
$str1是一个数组,,之前没注意到,不好意思,你需要返回$str1[0]就行了
Powered by& 执行一个正则表达式搜索并且使用一个回调进行替换
PHP preg_replace_callback 执行一个正则表达式搜索并且使用一个回调进行替换
preg_replace_callback
preg_replace_callback & 执行一个正则表达式搜索并且使用一个回调进行替换
preg_replace_callback
[, int $limit = -1
[, int &$count
要搜索的模式, 可以使字符串或一个字符串数组.
一个回调函数, 在每次需要替换时调用, 调用时函数得到的参数是从subject
中匹配到的结果. 回调函数返回真正参与替换的字符串.
你可能经常会需要callback函数而
仅用于preg_replace_callback()一个地方的调用. 在这种情况下, 你可以
使用来定义一个匿名函数作
为preg_replace_callback()调用时的回调. 这样做你可以保留所有
调用信息在同一个位置并且不会因为一个不在任何其他地方使用的回调函数名称而污染函数名称空间.
Example #1 preg_replace_callback()和
&?php/*&一个unix样式的命令行过滤器,&用于将段落开始部分的大写字母转换为小写.&*/$fp&=&fopen("php://stdin",&"r")&or&die("can't&read&stdin");while&(!feof($fp))&{&&&&$line&=&fgets($fp);&&&&$line&=&preg_replace_callback(&&&&&&&&'|&p&s*w|',&&&&&&&&create_function(&&&&&&&&&&&&//&single&quotes&are&essential&here,&&&&&&&&&&&&//&or&alternative&escape&all&$&as&$&&&&&&&&&&&&'$matches',&&&&&&&&&&&&'return&strtolower($matches[0]);'&&&&&&&&),&&&&&&&&$line&&&&);&&&&echo&$line;}fclose($fp);?&
要搜索替换的目标字符串或字符串数组.
对于每个模式用于每个subject字符串的最大可替换次数.
默认是-1(无限制).
如果指定, 这个变量将被填充为替换执行的次数.
如果subject是一个数组,
preg_replace_callback()返回一个数组, 其他情况返回字符串.
错误发生时返回NULL.
如果查找到了匹配, 返回替换后的 目标字符串(或字符串数组), 其他情况subject
将会无变化返回.
Example #2 preg_replace_callback()示例
&?php//&将文本中的年份增加一年.$text&=&"April&fools&day&is&04/01/2002
";$text.=&"Last&christmas&was&12/24/2001
";//&回调函数function&next_year($matches){&&//&通常:&$matches[0]是完成的匹配&&//&$matches[1]是第一个捕获子组的匹配&&//&以此类推&&return&$matches[1].($matches[2]+1);}echo&preg_replace_callback(&&&&&&&&&&&&"|(d{2}/d{2}/)(d{4})|",&&&&&&&&&&&&"next_year",&&&&&&&&&&&&$text);?&
以上例程会输出:
April fools day is 04/01/2003
Last christmas was 12/24/2002
Example #3 preg_replace_callback()使用递归构造处理BB码的封装
&?php$input&=&"plain&[indent]&deep&[indent]&deeper&[/indent]&deep&[/indent]&plain";function&parseTagsRecursive($input){&&&&/*&译注:&对此正则表达式分段分析&&&&&*&首尾两个#是正则分隔符&&&&&*&[indent]&匹配一个原文的[indent]&&&&&*&((?:[^[]|[(?!/?indent])|(?R))+)分析:&&&&&*&&&&&&&&&(?:[^[]|[(?!/?indent])分析:&&&&&*&&&&&&&&&&&&&首先它是一个非捕获子组&&&&&*&&&&&&&&&&&&&两个可选路径,&一个是非[字符,&另一个是[字符但后面紧跟着不是/indent或indent.&&&&&*&&&&&&&&&(?R)&正则表达式递归&&&&&*&&&&&[/indent]&匹配结束的[/indent]&&&&&*&/&&&&$regex&=&'#[indent]((?:[^[]|[(?!/?indent])|(?R))+)[/indent]#';&&&&if&(is_array($input))&{&&&&&&&&$input&=&'&div&style="margin-left:&10px"&'.$input[1].'&/div&';&&&&}&&&&return&preg_replace_callback($regex,&'parseTagsRecursive',&$input);}$output&=&parseTagsRecursive($input);echo&$?&
- 执行一个正则表达式的搜索和替换
- 返回最后一个PCRE正则执行产生的错误代码
- Create an anonymous (lambda-style) function
类型的信息
PHP preg_replace_callback note #1
also note that when you are using this functionality in a class and you need variables in that class, you can use a non static function as callback. array($this, functionName) should be enough to call an function of the class.
Either use create_function if you require the code only once,
use a static class function if no need for accessing variables in that class. or use the array metioned earlier in my post for having access to class variables or other functions!
PHP preg_replace_callback note #2
I noticed that 'e' modifier use addslashed on result
function wyczysc_strongi($string) {
&&& if(mb_strlen($string,'UTF-8')&60) {
&& & && return $
&&& } else {
&& & && return '&strong&'.$string.'&/strong&';
$tresc = "&strong&fajna dupa's&/strong&";
$tresc = preg_replace("/&strong&(.*?)&/strong&/ie",'wyczysc_strongi("$1")',$tresc);
echo $tresc will give: &strong&fajna dupa's&/strong&
solution: $tresc = stripslashes($tresc);
after callback
PHP preg_replace_callback note #3
I needed a simple code to tidy up a string. It simply had to upper-case letters after dot. Simple code to do so:
$string = preg_replace_callback(
'|(?:.)(?:s*)(w{1})|Ui',
create_function('$matches', 'return ". ".strtoupper($matches[1]);'), ucfirst($string)
$string = 'lorem ipsum dolor sit amet, consectetur adipiscing elit. sed ullamcorper diam eu lorem varius nec porta elit iaculis.';
echo preg_replace_callback(
'|(?:.)(?:s*)(w{1})|Ui',
create_function('$matches', 'return ". ".strtoupper($matches[1]);'), ucfirst($string)
Will output: Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed ullamcorper diam eu lorem varius nec porta elit iaculis.
$string = 'lorem ipsum dolor sit amet, consectetur adipiscing elit.& & & & & & & && sed ullamcorper diam eu lorem varius nec porta elit iaculis.';
echo preg_replace_callback(
'|(?:.)(?:s*)(w{1})|Ui',
create_function('$matches', 'return ". ".strtoupper($matches[1]);'), ucfirst($string)
Will output: Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed ullamcorper diam eu lorem varius nec porta elit iaculis.
Nothing fancy, but useful :)
PHP preg_replace_callback note #4
The pcre.backtrack_limit option (added in PHP 5.2) can trigger a NULL return, with no errors. The default pcre.backtrack_limit value is 100000. If you have a match that exceeds about half this limit it triggers a NULL response.
e.g. My limit was at 100000 but 500500 triggered a NULL response. I'm not running unicode but I *guess* PCRE runs in utf-16.
PHP preg_replace_callback note #5
Created this to fetch the link and name of an anchor tag. I use this when cleaning an HTML email to text. Using regex for HTML is not recommended but for this purpose I see no issue with it. This is not designed to work for nested anchors.
A note to keep in mind:
I was primarily concerned with valid HTML so if attributes do no use ' or " to contain the values then this will need to be tweaked.
If you can edit this to work better, please let me know.
function replaceAnchorsWithText($data) {
&&& $regex& = '/(&as*'; $regex .= '(.*?)s*'; $regex .= 'href=['"]+?s*(?P&link&S+)s*['"]+?'; $regex .= 's*(.*?)s*&s*'; $regex .= '(?P&name&S+)'; $regex .= 's*&/a&)/i'; if (is_array($data)) {
&& & && $data = "{$data['name']}({$data['link']})";
&&& return preg_replace_callback($regex, 'replaceAnchorsWithText', $data);
$input& = 'Test 1: &a href="http: //php.net1"&PHP.NET1&/a&.&br /&';
$input .= 'Test 2: &A name="test" HREF='HTTP: //PHP.NET2' target="_blank"&PHP.NET2&/A&.&BR /&';
$input .= 'Test 3: &a hRef=http: //php.net3&php.net3&/a&&br /&';
$input .= 'This last line had nothing to do with any of this';
echo replaceAnchorsWithText($input).'&hr/&';
Will output:
Test 1: PHP.NET1(http: //php.net1).
Test 2: PHP.NET2(HTTP: //PHP.NET2).
Test 3: php.net3 (is still an anchor)
This last line had nothing to do with any of this
PHP preg_replace_callback note #6
The good version of the class PhpHex2Str
class PhpHex2Str
&&& private $strings;
&&& private static function x_hex2str($hex) {
&& & && $hex = substr($hex[0], 1);
&& & && $str = '';
&& & && for($i=0;$i & strlen($hex);$i+=2) {
&& & & & && $str.=chr(hexdec(substr($hex,$i,2)));
&& & && return $str;
&&& public function decode($strings = null) {
&& & && $this-&strings = (string) $strings;
&& & && return preg_replace_callback('#\%[a-zA-Z0-9]{2}#', 'PhpHex2Str::x_hex2str', $this-&strings);
$obj = new PhpHex2Str;
$strings = $obj-&decode($strings);
var_dump($strings);
PHP preg_replace_callback note #7
Decode Hexa to Strings =)
class PhpHex2Str
&&& private $strings;
&&& private function x_hex2str($hex) {
&& & && $hex = substr($hex[0], 1);
&& & && $str = '';
&& & && for($i=0;$i & strlen($hex);$i+=2) {
&& & & & && $str.=chr(hexdec(substr($hex,$i,2)));
&& & && return $str;
&&& public function decode($strings = null) {
&& & && $this-&strings = (string) $strings;
&& & && return preg_replace_callback('#\%[a-zA-Z0-9]{2}#', 'x_hex2str', $this-&strings);
$strings = 'a %20 b%0A h %27 h %23';
$obj = new PhpHex2Str;
$strings = $obj-&decode($strings);
var_dump($strings);
PHP preg_replace_callback note #8
If you're looking to show only the first digit and last four digits of a credit card number (4xxxxxxxxxxxx2331) use something like this:
preg_replace_callback('/((.)(.*))?(.{4})/', create_function('$x', 'return $x[2].str_repeat("x", strlen($x[3])).$x[4];'), '$CCNUMBER')
PHP preg_replace_callback note #9
When you use preg_replace_callback in a class and have the callback function as a private method of that class, you need to set the callback function name like className::CallBack.
self::CallBack does not work and returns an error:
"Cannot call method self::CallBack() or method does not exist"!
class myClass{
&&& public function parsetext($text){
&& & && return preg_replace_callback('|([a-c])|i', 'myClass::preg_tolower', $text);
&&& public function parsefail($text){
&& & && return preg_replace_callback('|([a-c])|i', 'self::preg_tolower', $text);
&&& private static function preg_tolower($matches){
&& & && return strtolower($matches[1]);
$parser = new myClass;
echo $parser-&parsetext('ABCDEFGH');
echo $parser-&parsefail('ABCDEFGH');
PHP preg_replace_callback note #10
A simple function to replace a list of complete words or terms in a string (for PHP 5.3 or above because of the closure):
function replace_words($list, $line, $callback) {
&&& return preg_replace_callback(
&& & && '/(^|[^\w\-])(' . implode('|', array_map('preg_quote', $list)) . ')($|[^\w\-])/mi',
&& & && function($v) use ($callback) { return $v[1] . $callback($v[2]) . $v[3]; },
&& & && $line
Example of usage:
$list = array('php', 'apache web server');
$str = "php and the apache web server work fine together. php-gtk, for example, won't match. apache web servers shouldn't too.";
echo replace_words($list, $str, function($v) {
&&& return "&strong&{$v}&/strong&";
PHP preg_replace_callback note #11
This function does not support named subpatterns, so you can't do
preg_replace_callback('/(?&char&[a-z])/', 'callback', 'word');
function callback($matches) {
&&& var_dump($matches);
and expect to get $matches['char'] in your function.
PHP preg_replace_callback note #12
If you're planning to use preg_replace_callback inside a class, you need to use the array() function:
class MyClass
& function preg_callback_url($matches)
&&& $url = $matches[1].$matches[2];
&&& $text = '';
&&& $pos = strpos($url,' ');
&&& if ($pos!==FALSE) {
&& && $text = trim(substr($url,$pos+1));
&& && $url = substr($url,0,$pos);
&&& return '&a href="'.$url.'" rel="nofollow"&'.(($text!='') ? $text : $url).'&/a&';
& function ParseText($text)
&&& return preg_replace_callback('/[(http|https|ftp)(.*?)]/iS',array( &$this, 'preg_callback_url'), $text);
PHP preg_replace_callback note #13
This is what i use to read log files and do dns lookups on the ip's from the file.
function resolve_logs($arr) {
&& & && return gethostbyaddr($arr[0]);
$logent=file('yourlogfile');
$ipaddr = '/d{1,3}.d{1,3}.d{1,3}.d{1,3}/';
$logent = preg_replace_callback($ipaddr, resolve_logs, $logent);
PHP preg_replace_callback note #14
When you access variables from outside in a callback function, use the $global keyword:
global $x;
$str = '&Bla bla. &#x25';
$find = '/(&)([^#])/';
$replace = create_function('$f',
&&& 'global $x; $x ++; return $f[2];';
$str2 = preg_replace_callback($find, $replace, $str);
PHP preg_replace_callback note #15
To access a local variable within a callback, use currying (delayed argument binding). For example
function curry($func, $arity) {
&&& return create_function('', "
&& & && $args = func_get_args();
&& & && if(count($args) &= $arity)
&& & & & && return call_user_func_array('$func', $args);
&& & && $args = var_export($args, 1);
&& & && return create_function('','
&& & & & && $a = func_get_args();
&& & & & && $z = ' . $args . ';
&& & & & && $a = array_merge($z,$a);
&& & & & && return call_user_func_array('$func', $a);
&& & && ');
function on_match($transformation, $matches)
&&& return $transformation[strtolower($matches[1])];
$transform = array('a' =& 'Well,', 'd'=&'whatever', 'b'=&' ');
$callback = curry(on_match, 2);
echo preg_replace_callback('/([a-z])/i', $callback($transform), 'Abcd');
"Well, whatever"
The magic lies in this curry function I found here:
PHP preg_replace_callback note #16
To access a local variable within a callback, use currying (delayed argument binding). For example
function curry($func, $arity) {
&&& return create_function('', "
&& & && $args = func_get_args();
&& & && if(count($args) &= $arity)
&& & & & && return call_user_func_array('$func', $args);
&& & && $args = var_export($args, 1);
&& & && return create_function('','
&& & & & && $a = func_get_args();
&& & & & && $z = ' . $args . ';
&& & & & && $a = array_merge($z,$a);
&& & & & && return call_user_func_array('$func', $a);
&& & && ');
function on_match($transformation, $matches)
&&& return $transformation[strtolower($matches[1])];
$transform = array('a' =& 'Well,', 'd'=&'whatever', 'b'=&' ');
$callback = curry(on_match, 2);
echo preg_replace_callback('/([a-z])/i', $callback($transform), 'Abcd');
"Well, whatever"
The magic lies in this curry function I found here:
PHP preg_replace_callback note #17
To spend more than one parameter can do the following (note the "e" parameter in preg_replace function)
$array = array(
3=&'Three'
function search(&$array, $str, $foo, $bar){
&&& return ( empty($array[$str]) ? '['.$foo.'-'.$bar.']' : $array[$str] );
function keys(&$array, $str,$foo,$bar){
&&& return preg_replace('/[(.*?)]/e',"search($array,$1,$foo,$bar)",$str);
$str = "One [1] Two [2] Three [3], Other parameter [22]";
echo keys($array, $str,'Foo','Bar');
PHP preg_replace_callback note #18
The first example is bad, because it creates function for every line it processes. When the file has many lines, you could easily run out of memory. The code should be changed so, that create_function() is used outside of loop.
PHP preg_replace_callback note #19
preg_replace_callback returns NULL when pcre.backtrack_ this sometimes occurs faster then you might expect. No er so don't forget to check for NULL yourself
PHP preg_replace_callback note #20
it is much better on preformance and better practice to use the preg_replace_callback function instead of preg_replace with the e modifier.
function a($text){return($text);}
// 2.76 seconds to run 50000 times
preg_replace("/{(.*?)}/e","a('\1','\2','\3',$b)",$a);
// 0.97 seconds to run 50000 times
preg_replace_callback("/{(.*?)}/s","a",$a);
PHPPCRE - 函数

我要回帖

更多关于 preg replace 替换 的文章

 

随机推荐