【问题标题】:Regex to replace function name in PHP classes正则表达式替换 PHP 类中的函数名
【发布时间】:2018-03-09 16:59:03
【问题描述】:

我正在将 PHP5 应用程序转换为 PHP7,其中一项要求是删除与类同名的构造函数的所有实例,而是将其命名为“__construct”。

例如:

class xyz {
    public function xyz() {

需要成为

class xyz {
    public function __construct() {

我认为将 egrep 导入 sed 可能是“整体”执行此操作的最佳方式,但我对此都不太了解。

我知道我可以使用:

class\s+([A-Za-z]+)\s+\{

捕获类的名称,但我不确定从那里去哪里。

非常感谢任何帮助。

:)

【问题讨论】:

  • 是否可以选择使用脚本语言(例如PHP)?
  • 是的,我宁愿不重新发明轮子

标签: regex sed grep pcre


【解决方案1】:

正如 cmets 中所说,最好使用脚本语言、一些逻辑和双因素方法:

  1. 使用递归方法将包括类名在内的类作为“一个整体”进行匹配
  2. __construct替换类名的函数


PHP:
<?php

$class_regex = '~
        ^\s*class\s+
        (?P<class>\S+)[^{}]+(\{
        (?:[^{}]*|(?2))*
        \})~mx';

$data = preg_replace_callback($class_regex, 
    function($match) {
        $function_regex = '~function\s+\K'.$match['class'].'~';
        return preg_replace($function_regex, '__construct', $match[0]);
    },
    $data);

echo $data;
?>

regex101.com 和整个code on ideone.com 上查看外部正则表达式的演示。

【讨论】:

    猜你喜欢
    • 2013-12-09
    • 2011-02-21
    • 1970-01-01
    • 1970-01-01
    • 2017-10-07
    • 2014-06-01
    • 2014-03-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多