Here is the situation. I have 2 files
content.php
<?php $my_var = "this is a variable"; ?>
<h1> php{my_var} </h1>
index.php
<?php include "content.php" ?>
The result should be:
<h1>this is a variable</h1>
I know how to work with preg_replace_callback. But I don't know how can I change php{my_var} with the value of $my_var.
All the logic should happens inside the index.php.
Edit
index.php
function replace_pattern($match)
{
what should I write here
}
echo preg_replace_callback("/php\:\{(.*)\}/", "replace_pattern", $Content);
Edit 2
Variables are not declare in the global scope
Note the added question-mark in the regular expression to make it less greedy.
$my_var = 'Hello World!';
// Get all defined variables
$vars = get_defined_vars();
$callback = function($match) use ($vars)
{
$varname = $match[1];
if (isset($vars[$varname])) {
return $vars[$varname]; // or htmlspecialchars($vars[$varname]);
} else {
return $varname . ' (doesn\'t exists)';
}
};
echo preg_replace_callback("/php\:\{(.*?)\}/", $callback, $Content);
Demo: http://phpfiddle.org/main/code/ax15-bpyw
Try this:
$my_var = "this is a variable";
$string = '<h1> php{my_var} </h1>';
$pattern = '/php{(.*)}/i';
preg_match($pattern, $string, $match);
$varName = $match[1];
$newString= preg_replace($pattern, $$varName, $string);
echo $newString;
But, warning!
In this case, i assume, if the code is php{somethin}, then there should be a $something variable. I used dynamic variable name. If you want to use only $my_var then use like this:
$newString= preg_replace($pattern, $my_var, $string);
Related
I want to write my own little translation function.
My JSON File looks like:
{
"start": {
"body": {
"headline": "Hello, world!"
}
}
}
In my PHP Frontend, i want to write just Placeholders for translated Strings. So id do
<h1><?php trans('start.body.headline'); ?></h1>
My PHP Function is simple and looks like:
function trans($string) {
if (!isset($_GET['langID']))
$lang = 'de';
else
$lang = $_GET['langID'];
$str = file_get_contents('lang/'. $lang . '.json');
$json = json_decode($str);
$string = str_replace('.', '->', $string);
echo $json->$string;
}
But I don't get a Result.
The $string in My Function is correctly:
start->body->headline
And when I write:
echo $json->start->body->headline;
I get "Hello, world".
echo $json->$string;
is the same but doesn't work. why?
becouse you are using the some variable name $string for function parameter , use the other variable name here.
$keyword = str_replace('.', '->', $string);
echo $json->{$keyword};
also you can use return method
function trans($string) {
if (!isset($_GET['langID']))
$lang = 'de';
else
$lang = $_GET['langID'];
$str = file_get_contents('lang/'. $lang . '.json');
$json = json_decode($str);
$keyword = str_replace('.', '->', $string);
return $json->{$keyword};
}
and than use short way of echo in html
<h1><?= trans('start.body.headline'); ?></h1>
Given the following example:
public function replaceMyText($search, $replace, &$content)
{
$newContent = str_replace($search, $replace, $content, $count = 1)
$content = $newContent;
}
Can this cause a Warning that only variables can be passed by reference? If so, I can't fully understand why.
Should I assigned the $content to another variable before passing it to the str_replace function?
<?php
function replaceMyText($search, $replace, &$content)
{
$newContent = str_replace($search, $replace, $content, $count = 1);
$content = $newContent;
}
replaceMyText("123", "456", "123456");
using this function without variable will get a fatal error
Fatal error: Only variables can be passed by reference in /usercode/file.php on line 8
because
No other expressions should be passed by reference, as the result is undefined.
from http://php.net/manual/en/language.references.pass.php
you just can using by this
$a = "123456";
replaceMyText("123", "456", $a);
echo $a;
Sorry for my bad english. I hope it can help you.
EDIT
Please try this code :
function replaceMyText($search, $replace, $content)
{
$newContent = str_replace($search, $replace, $content,$count=1);
return $newContent;
}
$searchValue = "test";
$replaceWith = "magic trick";
$actualContent = "This is a test.";
$replaced = replaceMyText($searchValue,$replaceWith,$actualContent);
echo $replaced;
I am using PHP 7.2.4, I want to make a template engine project,
I try to use preg_replace to change the variable in the string,
the code is here:
<?php
$lang = array(
'hello' => 'Hello {$username}',
'error_info' => 'Error Information : {$message}',
'admin_denied' => '{$current_user} are not Administrator',
);
$username = 'Guest';
$current_user = 'Empty';
$message = 'You are not member !';
$new_string = preg_replace_callback('/\{(\$[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*)\}/', 'test', $string);
function test($matches)
{
return '<?php echo '.$matches[1].'; ?>';
}
echo $new_string;
But it just show me
Hello , how are you?
It automatically remove the variable...
Update:
here is var_dump:
D:\Wamp\www\t.php:5:string 'Hello <?php echo $username; ?>, how are you?' (length=44)
You may use create an associative array with keys (your variables) and values (their values), and then capture the variable part after $ and use it to check in the preg_replace_callback callback function if there is a key named as the found capture. If yes, replace with the corresponding value, else, replace with the match to put it back where it was found.
Here is an example code in PHP:
$values = array('username'=>'AAAAAA', 'lastname'=>'Smith');
$string = 'Hello {$username}, how are you?';
$new_string = preg_replace_callback('/\{\$([a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*)}/', function($m) use ($values) {
return 'Hello <?php echo ' . (!empty($values[$m[1]]) ? $values[$m[1]] : $m[0]) . '; ?>';
}, $string);
var_dump($new_string);
Output:
string(47) "Hello Hello <?php echo AAAAAA; ?>, how are you?"
Note the pattern charnge, I moved the parentheses after $:
\{\$([a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*)}
^ ^
Actually, you may even shorten it to
\{\$([a-zA-Z_\x7f-\xff][\w\x7f-\xff]*)}
^^
Do you want something like this?
<?php
$string = 'Hello {$username}, how are you?';
$username = 'AAAAAA';
$new_string = preg_replace('/\{(\$[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*)\}/', $username, $string);
echo $new_string;
The result is:
Hello AAAAAA, how are you?
The more simple way would be to just write
<?php
$username = 'AAAAAA';
$string = 'Hello '.$username.', how are you?';
I'm a fan of keeping it simple so I would use str_replace since it will also change all instances which may come in handy as you go forward.
$string = 'Hello {$username}, how are you?';
$username = 'AAAAAA';
echo str_replace('{$username}',$username,$string);
Can anyone see what i have done incorreclty using this class it should change the word before to after but it just sits there doing nothing.
The second php pgm is the actual classs I am using..
<?php
include("parse.inc.php");
$bob = new parseClass();
$tag = "{Before}";
$replacement = "After";
$content = "My animal runs around all over the place and his name is {Before}.";
$bob->ReplaceTag($tag, $replacement, $content);
echo $bob;
?>
parse.inc.php (file name)
***************************
<?php
Class parseClass {
function ReplaceTag($tag, $replacement, $content) {
$content = str_replace($tag, $replacement, $content);
return $content;
}
}
// END Class parseClass
?>
In your case, you pass the content into class's function
Therefore, you should store the return value into variable first
$result = $bob->ReplaceTag($tag, $replacement, $content);
echo $result;
You just need to store the result of your function in a local variable, and print that.
$result = $bob->ReplaceTag($x, $y, $z);
print($result);
I guess you want to print the string having be replaced,so you should :
$result = $bob->ReplaceTag($tag, $replacement, $content);
echo $result;
Why are you use echo to print class?If you want to do this,please use "var_dump" or 'print_r' instead;
If the hard requirement is that you want to be able to echo the instance of parseClass, try this:
class parseClass
{
private $content;
public function ReplaceTag($tag, $replacement, $content)
{
$this->content = str_replace($tag, $replacement, $content);
}
public function __toString()
{
return $this->content;
}
}
$bob = new parseClass();
$tag = "{Before}";
$replacement = "After";
$content = "My animal runs around all over the place and his name is {Before}.";
$bob->ReplaceTag($tag, $replacement, $content);
echo $bob;
For reference, see:
http://php.net/manual/en/language.oop5.magic.php#object.tostring
Simply replace these two lines
$bob->ReplaceTag($tag, $replacement, $content);
echo $bob;
with
$content = $bob->ReplaceTag($tag, $replacement, $content);
echo $content;
I made the following PHP function:
<?php
function convertGET($str) {
$regex = '/GET:+([a-zA-Z0-9_]+)/';
$str = preg_replace($regex, $_GET["$1"], $str);
return($str);
}
$string = "foobar: GET:foobar";
$string = convertGET($string);
echo $string;
?>
The function is suppost to get a string and replace something like:
GET:foobarwith the $_GET variable "foobar".
Use preg_replace_callback() instead:
<?php
$input = array("foobar" => "Some other string");
$regex = '~GET:([a-zA-Z0-9_]+)~';
$string = "foobar: GET:foobar";
$string = preg_replace_callback($regex,
function($matches) use ($input) {
return $input[$matches[1]];
},
$string);
echo $string;
// output: foobar: Some other string
?>
See a demo on ideone.com.