calling function inside preg_replace thats inside a function
You can use the "e" modifier on preg_replace()
(see Pattern Modifiers)
return preg_replace("/\[video\](.+?)\[\/video\]/e", "embed_video('$1')", $Text);
which tells preg_replace()
to treat the second parameter as PHP code.
How to call a function within preg_replace()?
I have created a demonstration to show how to call getOpenGraph()
and how the capture groups are passed as arguments without specifying them in the second parameter of preg_replace_callback()
.
I modified the pattern delimiters so that the slash in the end tag doesn't need to be escaped.
function getOpenGraph($matches){
return strrev($matches[1]); // just reverse the string for effect
}
$input='Leading text [ourl]This is ourl-wrapped text[/ourl] trailing text';
$pattern='~\[ourl\](.*?)\[/ourl\]~i';
$output=preg_replace_callback($pattern,'getOpenGraph',$input);
echo $output;
Output:
Leading text txet depparw-lruo si sihT trailing text
Trying to call a function inside preg_replace
If I understand you correctly, you want to execute user()
function on each match? As mentioned in comments, use the preg_replace_callback()
function.
<?php
$string = 'Hello [user=1]';
$s = preg_replace_callback(
'/\[user=(.*?)\]/is',
function($m) {return user('textlink', $m[1]);},
$string
);
echo $s;
PHP: Call function inside preg_replace
$txt = preg_replace_callback('#<!--dle_video_begin:(.+?)-->(.+?)<!--dle_video_end-->#is', function($matches){
return "[video=videoD({$matches[1]})]";
}, $txt);
Problem with function call inside preg_replace
You need to set the e modifier to have the substitution expression to be executed:
preg_replace('"\b(http://\S+)"e', '"<a href=\\"$1\\">".findTopDomain("$1")."</a>"', $text)
Note that your substitution now has to be a valid PHP expression. In this case the expression would be evaluated to:
"<a href=\"$1\">".findTopDomain("$1")."</a>"
And don’t forget to escape the output with at least htmlspecialchars
:
preg_replace('"\b(http://\S+)"e', '"<a href=\\"".htmlspecialchars("$1")."\\">".htmlspecialchars(findTopDomain("$1"))."</a>"', $text)
Preg_replace call function in same class?
I think your script might be entering an infinite loop. If you look in your get function, you're calling this:
$replace[] = $this->get('header');
So in the middle of a get call, you're pulling in the header. This then executes the exact same function which will itself pull in the header, over and over, over and over. You might want to disable this line for when $template
is 'header':
while ($templates = mysql_fetch_array($query)) {
$content = $templates['content'];
// If this is the header, stop here
if ($template == 'header')
return $content;
// Rest of loop...
}
If you want to perform regular expressions, add this after the while loop:
if ($template == 'header') {
$pattern = "/\[template\](.*?)\[\/template\]/is";
$replace = 'WHATEVER YOU WANT TO REPLACE IT WITH';
return preg_replace($pattern, $replace, $templates['content']);
}
How to pass parameter in preg_replace to a function in PHP?
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';
}
}
How to call a function in an preg_replace?
As I (and many others) told in comments, you have to use preg_replace_callback in this case. One possible approach:
$template = '<div> [BILD="123"][BILD="246"] </div>';
$pat = '/\[BILD="(.*?)"\]\[BILD="(.*?)"\]/';
return preg_replace_callback($pat, function($matches) use($id, $config) {
return getImageArea($id, $config, $matches[1], $matches[2]);
}, $template);
Demo. As you see, it's quite straight-forward; the only catch is making $id
and $config
variables available inside the callback (which is done with use
op).
Related Topics
Efficiently Pick N Random Elements from PHP Array (Without Shuffle)
How to Store a Variable in PHP Using Session
How to Read Gzip-Ed Response from Stackoverflow API in PHP
Decrementing Alphabetical Values
Inkscape Inside PHP/Apache Doesn't Render Fonts to Png
Using PHP to Execute Multiple MySQL Queries
How to Get All Combinations from Multiple Arrays
Implicit Class Variable Declaration in PHP
PHP Variable Inside Echo 'HTML Code'
PHP What Is the Best Approach to Using Xml? Need to Create and Parse Xml Responses
Create Blog Post Links Similar to a Folder Structure
Replace Woocommerce_Add_Order_Item_Meta Hook in Woocommerce 3.4
Facebook Connect- $User_Id = $Facebook->Getuser(); Always Returning 0
Reverse the Letters in Each Word of a String
MySQL - Access Denied for User