Issue
I want to do something like this:
I have this string:
Lorem ipsum {shortcode 42} dolor sit amet.
I want to parse it like this:
preg_replace('/\{shortcode (\d+)\}/i', MyClass::myFunction('$1') , $content);
The MyClass
code looks like this:
class MyClass {
public static function myFunction(string $id) {
// ...
return 'hello world';
}
}
But in the myFunction()
the $id
will always the $1
string, and not the content of the original $1
, what is a number.
How can I pass the preg_replace replacement value in parameter to my function?
Solution
Without rewriting your class method, use an anonymous function in preg_replace_callback
to call your method using index 1
as the first capture group match:
$result = preg_replace_callback('/\{shortcode (\d+)\}/i',
function($m) {
return MyClass::myFunction($m[1]);
}, $content);
Or you can call the static method, but then you would need to use the 1
index of the argument there:
// ['MyClass', 'myFunction'] or 'MyClass::myFunction'
$result = preg_replace('/\{shortcode (\d+)\}/i', ['MyClass', 'myFunction'], $content);
class MyClass {
public static function myFunction(array $array) {
// use $array[1]
return 'hello world';
}
}
Answered By - AbraCadaver Answer Checked By - Willingham (PHPFixing Volunteer)
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.