search
HomeBackend DevelopmentPHP Tutorialpreg_replace如何替换成preg_replace_callback

小弟以前从事Delphi开发,被社会所迫学习了PHP,今天当头一棒直接蒙了。
这个怎么改啊,程序报错需要将preg_replace替换成preg_replace_callback

$fields = preg_replace('/([a-zA-Z0-9_]+)\.([a-zA-Z0-9_*]+)/e', "\$this->_getFieldTable('\\1') . '.\\2'", $fields);


回复讨论(解决方案)

这太难了!!!!

$fields = preg_replace('/([a-zA-Z0-9_]+)\.([a-zA-Z0-9_*]+)/', function($r) {  return $this->_getFieldTable($r[1]) . $r[2];  }, $fields);

$fields = preg_replace('/([a-zA-Z0-9_]+)\.([a-zA-Z0-9_*]+)/', function($r) {  return $this->_getFieldTable($r[1]) . $r[2];  }, $fields);

报错
Object of class Closure could not be converted to string

那你原来就报错

$fields = preg_replace_callback('/([a-zA-Z0-9_]+)\.([a-zA-Z0-9_*]+)/', array($this, "_getFieldTable"), $fields);

不过_getFieldTable要改一下了,因为接收的是一个数组了。

附源码,大神帮我看看

**     *    获取查询时的字段列表     *     *    @author    Garbin     *    @param     string $src_fields_list     *    @return    string     */    function getRealFields($src_fields_list)    {        $fields = $src_fields_list;        if (!$src_fields_list)        {            $fields = '';        }        //$fields = preg_replace('/([a-zA-Z0-9_]+)\.([a-zA-Z0-9_*]+)/e', "\$this->_getFieldTable('\\1') . '.\\2'", $fields);		$fields = preg_replace_callback('/([a-zA-Z0-9_]+)\.([a-zA-Z0-9_*]+)/', function($r) {return $this->_getFieldTable($r[1]) . $r[2];}, $fields);	        //$fields = preg_replace_callback('/([a-zA-Z0-9_]+)\.([a-zA-Z0-9_*]+)/',function($r){ return $this->_getFieldTable($r(1) . $r(2));}, $fields);		return $fields;    }    /**     *    解析字段所属     *     *    @author    Garbin     *    @param     string $owner     *    @return    string     */    function _getFieldTable($owner)    {        if ($owner == 'this')        {            return $this->alias;        }        else        {            $m =& m($owner);            if ($m === false)            {                /* 若没有对象,则原样返回 */                return $owner;            }            return $m->alias;        }    }

15,16行我是用xuzuning大神的。


        //$fields = preg_replace('/([a-zA-Z0-9_]+)\.([a-zA-Z0-9_*]+)/e', "\$this->_getFieldTable('\\1') . '.\\2'", $fields);        $fields = preg_replace_callback('/([a-zA-Z0-9_]+)\.([a-zA-Z0-9_*]+)/', function($r) {return $this->_getFieldTable($r[1]) . $r[2];}, $fields);           //$fields = preg_replace_callback('/([a-zA-Z0-9_]+)\.([a-zA-Z0-9_*]+)/',function($r){ return $this->_getFieldTable($r(1) . $r(2));}, $fields);        return $fields;


组合的查询语句是这个样子的
MySQL Error[1054]: Unknown column 'user_privprivs' in 'field list' MySQL Query:SELECT user_privprivs, sstore_name,user_privuser_id,s.store_id FROM ecm_store s LEFT JOIN ecm_user_priv user_priv ON s.store_id = user_priv.store_id WHERE user_priv.user_id IN ('1') ORDER BY sstore_id DESC Wrong File: \eccore\model\mysql.php[534]


正确的应该是这个样子
SELECT user_priv.privs, s.store_name,user_priv.user_id,s.store_id FROM ecm_store s LEFT JOIN ecm_user_priv user_priv ON s.store_id = user_priv.store_id WHERE user_priv.user_id IN ('1') ORDER BY s.store_id DESC

错误的问题是: user_priv.privs和user_priv.user_id和s.store_id重点引用“.”都没有了。

噢,漏了个点

$fields = preg_replace('/([a-zA-Z0-9_]+)\.([a-zA-Z0-9_*]+)/', function($r) {  return $this->_getFieldTable($r[1]) . ".$r[2]";  }, $fields);

最后一个,谢谢xuzuning大神。最后面的preg_replace怎么替换

    /**     * 替换模块中图片路径     *     * @author liupeng     * @param  string  $source 内容     * @return string     **/    function smarty_prefilter_preCompile($source)    {        $file_type = strtolower(strrchr($this->_current_file, '.'));        $tmp_dir = '' ;        /* 替换文件编码头部 */        if (strpos($source, "\xEF\xBB\xBF") !== FALSE)        {            $source = str_replace("\xEF\xBB\xBF", '', $source);        }        if ($this->store_id > 0)        {            if (strpos($this->_current_file, '/mall/resource') !== false)            {                $mall_skin = $this->options['mall_skin'];                $tmp_dir = "themes/mall/skin/$mall_skin/" ;            }            else            {                $tmp_dir = "themes/store/skin/" . $this->skin . '/' ;            }        }        else {            $tmp_dir = "themes/mall/skin/" . $this->skin . '/' ;        }        $pattern = array(            '/<!--[^>|\n]*?({.+?})[^<|{|\n]*?-->/', // 替换smarty注释            '/<!--[^<|>|{|\n]*?-->/',               // 替换不换行的html注释            '/(href=["|\'])\.\.\/(.*?)(["|\'])/i',  // 替换相对链接            '/((?:background|src)\s*=\s*["|\'])(?:\.\/|\.\.\/)?(images\/.*?["|\'])/is', // 在images前加上 $tmp_dir            '/((?:background|background-image):\s*?url\()(?:\.\/|\.\.\/)?(images\/)/is', // 在images前加上 $tmp_dir            '/{nocache}(.+?){\/nocache}/ise', //无缓存模块            );        $replace = array(            '\1',            '',            '\1\2\3',            '\1' . $tmp_dir . '\2',            '\1' . $tmp_dir . '\2',            "'{insert name=\"nocache\" ' . '" . $this->_echash . "' . base64_encode('\\1') . '}'",            );        return preg_replace($pattern, $replace, $source);	    }

需要修改的只是最后一对:

$source = preg_replace_callback( '/{nocache}(.+?){\/nocache}/is', function($r) {    return '{insert name="nocache" '  . $this->_echash .  base64_encode($r[1]) . '}'; }, $source);

徐总给力啊,

    function fetch_str($source)    {        if (!defined('IS_BACKEND'))        {            $source = $this->smarty_prefilter_preCompile($source);        }        return preg_replace("/{([^\}\{\n]*)}/e", "\$this->select('\\1');", $source);    }

/e 就是 eval("return 串")
你脱去外层的引号就对了

function($r) {
  return $this->select($r[1]);
}

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
Working with Flash Session Data in LaravelWorking with Flash Session Data in LaravelMar 12, 2025 pm 05:08 PM

Laravel simplifies handling temporary session data using its intuitive flash methods. This is perfect for displaying brief messages, alerts, or notifications within your application. Data persists only for the subsequent request by default: $request-

cURL in PHP: How to Use the PHP cURL Extension in REST APIscURL in PHP: How to Use the PHP cURL Extension in REST APIsMar 14, 2025 am 11:42 AM

The PHP Client URL (cURL) extension is a powerful tool for developers, enabling seamless interaction with remote servers and REST APIs. By leveraging libcurl, a well-respected multi-protocol file transfer library, PHP cURL facilitates efficient execution of various network protocols, including HTTP, HTTPS, and FTP. This extension offers granular control over HTTP requests, supports multiple concurrent operations, and provides built-in security features.

Simplified HTTP Response Mocking in Laravel TestsSimplified HTTP Response Mocking in Laravel TestsMar 12, 2025 pm 05:09 PM

Laravel provides concise HTTP response simulation syntax, simplifying HTTP interaction testing. This approach significantly reduces code redundancy while making your test simulation more intuitive. The basic implementation provides a variety of response type shortcuts: use Illuminate\Support\Facades\Http; Http::fake([ 'google.com' => 'Hello World', 'github.com' => ['foo' => 'bar'], 'forge.laravel.com' =>

12 Best PHP Chat Scripts on CodeCanyon12 Best PHP Chat Scripts on CodeCanyonMar 13, 2025 pm 12:08 PM

Do you want to provide real-time, instant solutions to your customers' most pressing problems? Live chat lets you have real-time conversations with customers and resolve their problems instantly. It allows you to provide faster service to your custom

PHP Logging: Best Practices for PHP Log AnalysisPHP Logging: Best Practices for PHP Log AnalysisMar 10, 2025 pm 02:32 PM

PHP logging is essential for monitoring and debugging web applications, as well as capturing critical events, errors, and runtime behavior. It provides valuable insights into system performance, helps identify issues, and supports faster troubleshoot

Explain the concept of late static binding in PHP.Explain the concept of late static binding in PHP.Mar 21, 2025 pm 01:33 PM

Article discusses late static binding (LSB) in PHP, introduced in PHP 5.3, allowing runtime resolution of static method calls for more flexible inheritance.Main issue: LSB vs. traditional polymorphism; LSB's practical applications and potential perfo

Customizing/Extending Frameworks: How to add custom functionality.Customizing/Extending Frameworks: How to add custom functionality.Mar 28, 2025 pm 05:12 PM

The article discusses adding custom functionality to frameworks, focusing on understanding architecture, identifying extension points, and best practices for integration and debugging.

Framework Security Features: Protecting against vulnerabilities.Framework Security Features: Protecting against vulnerabilities.Mar 28, 2025 pm 05:11 PM

Article discusses essential security features in frameworks to protect against vulnerabilities, including input validation, authentication, and regular updates.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft