John Davidson

preg replace - php dynamic replacement with a std object

0 comments
Message:


How can I make a dynamic replacement with a std object?
I can't get how to use $1 in this case :(
See below.


$lang->custom_name = "Me";
$lang->custom_email = "Me@me";

$html = "hello {{custom_name}} with {{custom_email}} ";

$html = preg_replace("/{{(custom_.*)}}/", $lang->{'$1'} , $html);


My Answer:
php
// Define the std object
$replacement = new stdClass();
$replacement->name = 'John';
$replacement->age = 30;

// Define the string to be replaced
$string = 'Hello, my name is $name and I am $age years old.';

// Use preg_replace_callback to dynamically replace the placeholders with the std object properties
$result = preg_replace_callback('/\$(\w+)/', function($matches) use ($replacement) {
$property = $matches[1];
return isset($replacement->$property) ? $replacement->$property : $matches[0];
}, $string);

// Output the result
echo $result;


In this example, we define a stdClass object `$replacement` with properties `name` and `age`. We then define a string `$string` with placeholders `$name` and `$age`.

We use `preg_replace_callback` to dynamically replace the placeholders with the corresponding properties from the std object. Inside the callback function, we check if the property exists in the std object and return its value, otherwise we return the original placeholder.

Finally, we output the result which will be 'Hello, my name is John and I am 30 years old.'.

Rate this post

4 of 5 based on 5710 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us