The function extractBody() extracts the body part of a function:
$data = '
<?php
function my_function($param){
if($param === true){
// This is true
}else if($param === false){
// This is false
}else{
// This is not
}
}
?>
';
function extractBody($functionName, $data) {
$c = preg_match_all("/function\s+".$functionName."\s*\((?<param>[^\)]*)\)\s*(?<body>\{(?:[^{}]+|(?&body))*\})/", $data, $matches);
return $c > 0 ? $matches['body'] : null;
}
$body =extractBody("my_function", $data);
var_dump($body);
result: The variable $body
contains
if($param === true){
// This is true
}else if($param === false){
// This is false
}else{
// This is not
}
Now I need a second function to work with lambda functions (function is assigned to a variable)
$data2 = '
<?php
$my_function = function($param){
if($param === true){
// This is true
}else if($param === false){
// This is false
}else{
// This is not
}
}
?>
';
function extractBody2($functionName, $data) {
$c = preg_match_all("/".$functionName."\s+=\s+function\s+\s*\((?<param>[^\)]*)\)\s*(?<body>\{(?:[^{}]+|(?&body))*\})/", $data, $matches);
return $c > 0 ? $matches['body'] : null;
}
$body2 =extractBody2("my_function", $data2);
var_dump($body2);
Unfortunately, I'm not a regex specialist and I get NULL back.
I think the error must be somewhere here: "/".$functionName."\s+=\s+
regex101 didn't reveal any issues though.