PHP preg_replace string within variables - php

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);

Related

how to find and replace in the first word from the string in php

how to find and replace the first word from the string using php
eg:
$str = 'Super World Hello World';
replace($str,'Hello','Hi');
expected result should be 'Super World Hello World' as it does not match with first word.
eg2:
$str = 'Hello World Hello World';
replace($str,'Hello','Hi');
expected result should be 'Hi World Hello World' as it does match with first word.
please help
Create a function for this, passed 3 arguments. Logic is convert string into array by explode() function and get first element of the array by using array_shift() function and compare with search string
function getReplacedStr($str, $searchStr, $replaceWith){
$arr = explode(' ', $str);
$firstElement = array_shift($arr);
if($searchStr == $firstElement){
$finalStr = $replaceWith.' '.implode(' ', $arr);
}else{
$finalStr = $str;
}
return $finalStr;
}
$replaceWith = 'Hi';
$searchStr = 'Hello';
$str = 'Hello World Hello World';
$str2 = 'Super World Hello World';
echo getReplacedStr($str, $searchStr, $replaceWith);
echo "\n";
echo getReplacedStr($str2, $searchStr, $replaceWith);
Demo

Replace variable with its value inside HTML without <?php ?>

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);

How to create a function that can transform the last word into Uppercases?

How do i create a function replaceMe() in php that would turn:
$str = 'This is a very long string';
into:
'This is a very long STRING?'
can someone help me?
You apparently want to do a regular expression substitution, anchored at the end of the line. Use preg_replace:
$str = 'This is a very long string';
# This is a very long LINE
echo preg_replace("/string$/", "LINE", $str);
For a general case, you can provide a callback instead of a replacement string, and simply uppercase the matched substring with preg_replace_callback:
$str = 'This is a very long blah';
function word_to_upper($match) {
return strtoupper($match[1]);
}
# This is a very long BLAH
echo preg_replace_callback("/(\w+)$/", "word_to_upper", $str);
If you're using PHP 5.4 or greater, you can supply the callback as an anonymous function:
echo preg_replace_callback("/(\w+)$/", function ($match) {
return strtoupper($match[1])
}, $str);
This works:
$str = 'This is a very long string';
echo $str."<br/>";
function replaceMe($str = "")
{
$words = explode(" ",$str);
$totalwords = count($words)-1;
$lastword = $words[$totalwords];
$words[$totalwords] = strtoupper($lastword);
$str = implode(" ",$words);
return $str;
}
echo replaceMe($str);
?>
Output:
This is a very long string
This is a very long STRING
$str = 'This is a very long string.';
function lastWordUpper($str){
$temp = strrev($str);
$last = explode(" ", $temp, 2);
return strrev(strtoupper($last[0]). ' ' .$last[1]) ;
}
echo lastWordUpper($str);

PHP String Replacement

I wish to have one string that contains for instance (mystring):
file config.php
$mystring = "hello my name is $name and i got to $school";
file index.php
include('config.php');
$name = $_GET['name'];
$school = $_GET['school'];
echo $mystring;
Would this work ? or are there any better ways
$string = 'Hello, my name is %s and I go to %s';
printf($string, $_GET['name'], $_GET['school']);
or
$string = 'Hello, my name is :name and I go to :school';
echo str_replace(array(':name', ':school'), array($_GET['name'], $_GET['school']), $string);
You can automate that last one with something like:
function value_replace($values, $string) {
return str_replace(array_map(function ($v) { return ":$v"; }, array_keys($values)), $values, $string);
}
$string = 'Hello, my name is :name and I go to :school';
echo values_replace($_GET, $string);
No it won't work.
You have to define $name first before using it in another variable
config.php should look like
<?php
$name = htmlspecialchars($_GET['name']);
$school = htmlspecialchars($_GET['school']);
$mystring = "hello my name is $name and i got to $school";
and index.php like
<?php
include('config.php');
echo $mystring;
Why didn't you try it?
demo:
http://sandbox.phpcode.eu/g/2d9e0.php?name=martin&school=fr.kupky
Alternatively, you can use sprintf like this:
$mystring = "hello my name is %s and i got to %s";
// ...
printf($mystring, $name, $school);
This works because your $mystring literal is using double quotes, if you'd used single quotes then it would not work.
http://www.php.net/manual/en/language.types.string.php#language.types.string.parsing

String difference in PHP

I have an input string $foo which contains both alphanumeric and non-alphanumeric characters.
I use ereg_replace to $foo to replace all non-wanted chars with empty chars. Now I want to know what were these "erased" chars. How can I do this?
If you're using regex to replace, why don't you just use the same regex and do a "preg_match", then a "preg_replace"
You could use
$foo = "something";
$bar = ereg_replace(...);
array_diff(chunk_split($foo, 1), chunk_split($bar, 1));
In PHP 5.3:
$text = 'Hello, World!';
$stripped = '';
$text = preg_replace_callback('/([^A-Za-z0-9]+)/',
function($m) use (&$stripped) { $stripped .= $m[0]; return ''; }, $text);
echo "$text\n$stripped\n";
Output:
HelloWorld
, !

Categories