用于替换 PHP 类 中的函数名称的正则表达式
Regex to replace function name in PHP classes
我正在将 PHP5 应用程序转换为 PHP7,其中一个要求是删除与 class 具有相同名称的构造函数的所有实例,并取而代之将其命名为“__construct”。
例如:
class xyz {
public function xyz() {
需要成为
class xyz {
public function __construct() {
我认为将 egrep 通过管道传输到 sed 可能是执行此操作的最佳方法 "en masse",但我不太了解这样做。
我知道我可以使用:
class\s+([A-Za-z]+)\s+\{
捕获 class 的名称,但我不确定从那里去哪里。
非常感谢任何帮助。
:)
如评论中所述,最好使用脚本语言、一些逻辑和 two-factor-approach:
- 使用递归方法匹配 class,包括 class 名称作为 "a whole"
- 用 class 名称替换函数
__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 and for the whole code on ideone.com 上查看外部正则表达式的演示。
我正在将 PHP5 应用程序转换为 PHP7,其中一个要求是删除与 class 具有相同名称的构造函数的所有实例,并取而代之将其命名为“__construct”。
例如:
class xyz {
public function xyz() {
需要成为
class xyz {
public function __construct() {
我认为将 egrep 通过管道传输到 sed 可能是执行此操作的最佳方法 "en masse",但我不太了解这样做。
我知道我可以使用:
class\s+([A-Za-z]+)\s+\{
捕获 class 的名称,但我不确定从那里去哪里。
非常感谢任何帮助。
:)
如评论中所述,最好使用脚本语言、一些逻辑和 two-factor-approach:
- 使用递归方法匹配 class,包括 class 名称作为 "a whole"
- 用 class 名称替换函数
__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 and for the whole code on ideone.com 上查看外部正则表达式的演示。