PHP: String to actual value - php

I am creating a function to parse text from a templating system, and add the corresponding values.
For example, the user might input hi [[first_name]] and the [[first_name]] part will be replaced with the actual first name.
Somehow, I parsed that and ended up with a text that looks like this:
hi $info['first_name']
The above is just as text though, what can I do to actually make $info['first_name'] be the value (I already have that array in there, but I am not sure how to convert string to PHP variable)
Thanks!

Use simple str_replace function:
$str = "hi [[first_name]]";
foreach (array_keys($info) as $key) {
$str = str_replace("[[".$key."]]", $info[$key], $str);
}
echo $str;

str_replace("[[first_name]]", $info['first_name'], 'hi [[first_name]]');
You haven't share your code but you may print the variable name instead of its value.

<?php
$myTemplate = "hi [[first_name]], how are you this fine [[day_of_week]]?";
$myData = array(
'[[first_name]]' => 'James'
,'[[day_of_week]]' => 'Friday'
);
echo str_replace(array_keys($myData), array_values($myData), $myTemplate);
?>

Related

Get value from Array inside of an Array

I have the following string output if I run print_r($val):
{"next_offset":-1,"records":[{"id":"e3266222-5389-11ed-ab30-0210c01ad3d2","name":"That is a nice name"}]}
Now, I need the value of attribute "id". Sounds simple but I'm not able getting there.
Does something like this work?
I'm assuming $val is a json string.
<?php
$val = "{\"next_offset\":-1,\"records\":[{\"id\":\"e3266222-5389-11ed-ab30-0210c01ad3d2\",\"name\":\"That is a nice name\"}]}";
$val = json_decode($val);
print_r($val->records[0]->id);
?>

Correct way of adding text + php variable in json string?

I am struggling a bit to find the correct way of adding a php variable in my json string, with text added just in front of the variable. This is what I have got so far...
$postData = '
{
"message": "Web order '.$order_number.'"
}
';
When I look at the printout there is a line break just after "Web order", but otherwise nothing seems to go wrong... is this the way to do it?
If you want to use json string, then make sure you have properly use your values in your array.
Example:
<?
$order_number = 1;
$yourArray = array('message'=>"Web order ".$order_number);
echo json_encode($yourArray);
?>
Result:
{"message":"Web order 1"}
Here, i am using an array for your data $yourArray and then use json_encode() for json string.
DEMO
Instead of concatenate string, use sprintf()
Dealing directly with Json can become very harmful quickly. Prefer to use array then json_encode instead.
in your case, here is a simple example:
$message = sprintf('Web order %s', $order_number)
$postData = [
'message' => $message
];
$json = json_encode($postData);

Change part of text from mysql into variable name using php

Totally lost on how to solve. I have a mysql text record which contains the following text:
Hello $someone
When I output it in php, it shows as Hello $someone - which is fine and what I expect.
However, how can I output it in php so that it turns $someone into a php variable, which is assigned in php?... So I'd like my php code like:
$someone = "John Doe";
echo $subject;
returns: Hello John Doe
I've tried looking at variable variables, using $$someone, ${$someone} but always just returns text.
I understand that $someone would always be a text, so would have to have it stored in mysql as something like {$someone} to differentiate it from a dollar amount like $50 etc.
Any help would be greatly appreciated!
Here's an exampe of a simple function that will replace placeholder values in a string. Both the strings ($text) and the data could easily come from the database.
$text = "";
$text .= "<p>Dear {name},</p>\n";
$text .= "<p>Thank you for your order on {order_date}.</p>\n";
$text .= "<p>You order was shipped on {ship_date}.</p>\n";
$data = array(
"name" => "John Doe",
"order_date" => "05/01/2018",
"ship_date" => "05/04/2018",
"order_total" => "$22.50"
);
$textToDisplay = curly_replacer($text,$data);
echo $textToDisplay;
// Function to replace placeholders with data values.
// $str contains placeholder names enclosed in { }
// $data is an associative array whose keys are placeholder,
// and values are the values to replace the placeholders
function curly_replacer($str,$data) {
$rslt = $str;
foreach($data as $key => $val) {
$rslt = str_replace("{".$key."}", $val, $rslt);
}
return $rslt;
}

db table names as alias in php GET-paramter?

I am looking for a possibility to pass db table name and column name via php and GET parameter.
I have a data grid with following structure:
table_name1.column1, table_name2.column1, table_name2.column1.
There is a search function for the grid, where I need those parameters.
From the url "?table_name1.column1=22" I am getting through the $_GET only table_name1_column1=22
How would you solve that?
Encode the variable with base64 and decode before you use.
I know that's dirty.
But php variables doesn't support periods (dots)
This is a documented feature of PHP. Its basically because PHP cannot have variable names with dots in them.
$x.y = 1 // is an invalid variable name
MANUAL Convert dots to _ in GET & POST
You can use serialize function of php to pass the text "table_name1.column1" in url. But for that you need to do few coding to get the result. Below I have given code which you can use:
Page1.php
<?php
$test = serialize('table_name1.column1=11::table_name2.column2=22');
?>
<a href='Page2.php?qs=<?php echo $test?>'>test</a>
Use this $test to pass as query string. In above example, I am passing on anchor tag click.
Page2.php
use following code to Unserialize the query string and use the values.
<?php
$test2 = unserialize($_GET['qs']);
$ex = explode('::',$test2);
$new_arr = array();
foreach($ex as $val)
{
$ex2 = explode('=',$val);
$new_arr[$ex2[0]] = $ex2[1];
}
echo $new_arr['table_name1.column1']; //print 11
echo $new_arr['table_name2.column2']; //print 22
?>
Hope this will help you :)
You need to seperate each parameter with &.
So: ?table=table_name1&column=column1

How to get my word from following string?

I have two strings in PHP:
$Str1 = "/welcome/files/birthday.php?business_id=0";
$Str2 = "/welcome/index.php?page=birthday";
I have to get word birthday from this two string with a single function.
I need a function which returns birthday on both case.
example
function getBaseWord($word){
...
return $base_word;
}
getBaseWord('/welcome/files/birthday.php?business_id=0');
getBaseWord('/welcome/index.php?page=birthday');
both function call should return "birthday".
How can i do it.
If I correctly understand what you are trying to do then this should do what you need:
function getWord(){
return $_GET['page'];
}
or $_GET['business_id'];
I think $_GET is an associative array made from the GET request that was sent to the page. An associative array is one where you access something like ['name of the element'] instead of [1] or [2] or whatever.
So what you will need to do is get all of the actual GET variables extracted from the string:
//Seperate the URL and the GET Data
list($url,$querystring) = explode('?', $string, 2);
//Seperate the Variable name from its value
list($GETName, $GETValue) = explode("=", $querystring);
//Check to see if we have the right variable name
if($GETName == "page"){
//Return the value of that variable.
return $GETValue;
}
NOTE
This is very BASIC and will not accept more then one GET parameter. You will need to modify it if you plan on have more variables.
I have no idea what you are talking about but, you can cut the word "birthday" with str_replace and replace with another word, or you can find the position with stripos, I have no idea what we are trying to do here, so those are the only things come to my mind

Categories