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;
}
Related
I have a string that contains variables in it, and I want to add the values of the variables into it, as I'm trying it, it simply spits out as a string instead of adding the values of the variables.
Here is my code
$vars = $item->toArray();
extract($vars);
echo ($message_tmpl);die;
echo print_r($message_tmpl)die;
Variables are extracted to add the values, but it returns plain output instead of values.
$first_name is extracted through $vars
Output
'My message to $first_name';
It should be
'My message to John Doe';
thanks
you can do this :
$name = "Toto";
$info["age"] = "8yo";
echo "Hello {$name} who is {$info["age"]}";
will output :
Hello Toto who is 8yo
You can also use the strtr() function such as :
$template = '$who likes $what';
$vars = array(
'$who' => 'Toto',
'$what' => 'fruits',
);
echo strtr($template, $vars);
you will get :
Toto likes fruits
I have a problem when returning a row from database that has a column type TEXT(in this case, column "details") which contains an array of JSON objects. Example:
{
productid: 1
shopid: 1
title: 'Product 1'
--> details: [{"name":"Brand name","value":"Brand value"},{"name":"Color","value":"blue"}]
. . .
}
Data inserted into database in columns of type TEXT are inserted like addslashes(json_encode($array_or_object)) to safely escape before insert.
When returning data, columns of type TEXT by function json_decode() and returned with no problem. Problem occurs when someone tries using single ' and double quotes " in details. Example:
details: [{"name":"\\\"test123\\\"","value":"\\\"test\\\" \\'test\\' \\\"test \\' test \\' t\\\"est"}]
Returned value looks like:
"details": [
{
"name": "\\\"test123\\\"",
"value": "\\\"test\\\" \\'test\\' \\\"test \\' test \\' t\\\"est"
}
],
I have more than one way of storing JSON data in database (as object, array of objects, array of arrays of objects,...), and I need a way to escape these backslashes.
Using stripslashes() on the string before using json_decode() does not work, it breaks the JSON.
Creating a recursive function works, but is not as pretty as I would like it to be. Example:
function decode_json($json) {
if (empty($json)) {
return $json;
}
if (is_string($json)) {
$json = json_decode($json, true);
}
foreach ($json as $key => $value) {
if (is_array($value)) {
$json[$key] = decode_json($value);
continue;
}
$json[$key] = stripslashes($value);
}
return $json;
}
Any help is appreciated.
json_encode already escape your string, you don't need to use addslashes()
Example:
$var = ["value" => "test'\""];
print_r(json_encode($var));
Result:
{"value":"test'\""}
And will be better to use PDO with bind parameters: https://www.php.net/manual/en/pdostatement.bindparam.php
and what exactly is the point of using a database, when storing the raw JSON?
decode first, then escape the values to insert - else you'll also escape all of the JSON delimiters,
which might subsequently cripple the whole input string and render it F.U.B.A.R.
PS: PDOStatement still requires PDO::quote() to escape the input properly.
I am working on a function to sanitize credit card data by replacing all digits except the last 4 with X's. the problem is that I have a lot of data already stored in the database as json objects. each record may or may not have a card number somewhere in it, and they occur in different places in the text from record to record (sometimes at the very end, sometimes in the middle, etc.) Looking for a way to extract all 15-digit or 16-digit numbers from the string so that I can pass this number to the sanitize function.
Looking for a way to extract all 15-digit or 16-digit numbers from the string
You can use:
\b[0-9]{15,16}\b
In PHP You can use like this:
<?php
$subject="aa999999999999999aa888888888888888as555555ssd555fs22aa999999999999999a";//Your string
preg_match_all('/(?:[0-9]{15,16})+/s', $subject, $result, PREG_PATTERN_ORDER);
$result = $result[0];
print_r($result);//Printing result
output:
Array ( [0] => 999999999999999 [1] => 888888888888888 [2] => 999999999999999 )
if you want only one and first number then you can use this instead:
if (preg_match('/([0-9]{15,16})/s', $subject, $regs)) {
$result = $regs[0];
} else {
$result = "";
}
If it is stored as a json object in the DB and you want to find an attribute in the object you'll want to use json_decode() to take the record and make it a php Stdclass.
so if the json record looks like this:
$record = "{ 'name' : 'theSpurg', 'cc_num' : '139764518623' }"
You can access it like this
$test = json_decode($record);
$credi_num = $test->cc_num;
if that's not what you're looking for then I am misunderstanding the situation.
Cheers
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);
?>
I have a function that takes the input of a user defined string and an array of data (key=>value), which looks like this;
$text = "Hi! My name is #name, and I live in #location.";
$dataArray = array("name" => "Mikal", "location" => "Oslo, Norway");
function MakeString($text, array $dataArray)
{
// return manipulated string...
}
I would like my function to swap the string #variables with data from the array, where string-variable matches array-key (if it does), so that the function returns:
"Hi! My name is Mikal, and I live in Oslo, Norway."
foreach($dataArray as $key=>$value)
{
$text= str_replace("#".$key,$value,$text);
}