PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Sunday, November 20, 2022

[FIXED] How to pass parameter in preg_replace to a function in PHP?

 November 20, 2022     php, preg-replace, regex     No comments   

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)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing