I'm storing some strings within a *.properties file. An example of a string is:
sendingFrom=Sending emails from {$oEmails->agentName}, to {$oEmails->customerCount} people.
My function takes the value from sendingFrom and then outputs that string on the page, however it doesn't automatically parse the {$oEmails->agentName} within. Is there a way, without manually parsing that, for me to get PHP to convert the variable from a string, into what it should be?
If you can modify your *.properties, here is a simple solution:
# in file.properties
sendingFrom = Sending emails from %s, to %s people.
And then replacing %s with the correct values, using sprintf:
// Get the sendingFrom value from file.properties to $sending_from, and:
$full_string = sprintf($sending_from, $oEmails->agentName, $oEmails->customerCount);
It allows you to separate the logic of your app (the variables, and how you get them) from your presentation (the actual string scheme, stored in file.properties).
Just an alternative.
$oEmails = new Emails('Me',4);
$str = 'sendingFrom=Sending emails from {$oEmails->agentName}, to {$oEmails->customerCount} people.';
// --------------
$arr = preg_split('~(\{.+?\})~',$str,-1,PREG_SPLIT_DELIM_CAPTURE);
for ($i = 1; $i < count($arr); $i+=2) {
$arr[$i] = eval('return '.substr($arr[$i],1,-1).';');
}
$str = implode('',$arr);
echo $str;
// sendingFrom=Sending emails from Me, to 4 people.
as others mentioned eval wouldn't be appropriate, I suggest a preg_replace or a preg_replace_callback if you need more flexibility.
preg_replace_callback('/\$(.+)/', function($m) {
// initialise the data variable from your object
return $data[$m[1]];
}, $subject);
Check this link out as well, it suggests the use of strstr How replace variable in string with value in php?
You can use Eval with all the usual security caviats
Something like.
$string = getStringFromFile('sendingFrom');
$FilledIn = eval($string);
Related
I'm localizing a website that I've built. I'm doing this by having a .lang file read and each line (syntax: key=string) is placed in a variable depending on the chosen language.
This array is then used to place the strings in the correct places.
The problem I'm having is that certain strings need to have hyperlinks in the middle of them for example someplace I've put my name that links to my contact page. Or a lot of the readouts of the website need to be in the strings.
To solve this I've defined a variable that holds the html + Forecaster + html,
and the localization file contains the $Forecaster variable in the string.
The problem with this as I promptly discovered is that it stubbornly refuses to parse the inline variables in the strings from the file.
Instead it prints the string and variable name as it looks in the file.
And I have yet to find a way to make it parse the variables.
For example "Heating up took $str_time" would be printed on the page exactly like that, instead of inputting the previously defined value of $str_time.
I currently use fopen() and fgets() to open and read the lines. I then explode them to separate the key and the string and then place these into the array.
Is there a way to make it parse the variables, or alternatively is there another way of reading the lines that allows for parsing the inline variables?
The code that gets the line and converts it to the array looks like this:
(It obviously loops through the lines)
#list($key, $string) = explode('=', $line);
$key = strtok($line, '=');
$string = strtok('=');
$local[$key] = $string;
$counter++;
echo $local[$key] . "<br>";
The counter is unused and the echo is for testing.
A line from the .lang file looks like this:
fuel.results.heatup.timeused=Heating up took $str_time
I would call the array where I want the string like this:
$local['fuel.results.heatup.timeused']
As you can see I've tried both explode and strtok but it hasn't made a difference.
Personally I'd write your text file in JSON format to make it easier to pull data out.
Here is a solution directly from the php manual: http://nz2.php.net/manual/en/function.eval.php
$string = 'cup';
$name = 'coffee';
$str = 'This is a $string with my $name in it.';
echo $str. "\n";
eval("\$str = \"$str\";");
echo $str. "\n";
It is worth noting that eval() can be very dangerous used in the wrong way so make sure you're code is very secure E.g. if someone altered your txt file with real PHP code they could execute it directly on the server.
Another approach would require you to know all your variable names and could then do something like:
$str = 'Heating up took $str_time';
echo 'str=' . str_replace('$str_time', $str_time, $str);
Or do this via an array:
$str = 'Heating up took $str_time as well as $other_value';
$vars = Array('str_time', 'other_value');
foreach($vars as $varName) {
$str = str_replace('$' . $varName, $$varName, $str);
}
echo 'str=' . $str;
If you not know all the variable name, you can use this example, without eval(). It is indicatred to avoid eval().
$str = 'fuel.results.heatup.timeused=Heating up took $str_time';
$str_time = 'value';
if(preg_match('/\$([a-z0-9_]+)/i', $str, $v)) {
$vname = $v[1];
$str = str_replace('$'.$vname, $$vname, $str);
}
echo $str; // fuel.results.heatup.timeused=Heating up took value
I am trying to use a License PHP System…
I will like to show the status of their license to the users.
The license Server gives me this:
name=Service_Name;nextduedate=2013-02-25;status=Active
I need to have separated the data like this:
$name = “Service_Name”;
$nextduedate = “2013-02-25”;
$status = “Active”;
I have 2 days tring to resolve this problem with preg_match_all but i cant :(
This is basically a query string if you replace ; with &. You can try parse_str() like this:
$string = 'name=Service_Name;nextduedate=2013-02-25;status=Active';
parse_str(str_replace(';', '&', $string));
echo $name; // Service_Name
echo $nextduedate; // 2013-02-25
echo $status; // Active
This can rather simply be solved without regex. The use of explode() will help you.
$str = "name=Service_Name;nextduedate=2013-02-25;status=Active";
$split = explode(";", $str);
$structure = array();
foreach ($split as $element) {
$element = explode("=", $element);
$$element[0] = $element[1];
}
var_dump($name);
Though I urge you to use an array instead. Far more readable than inventing variables that didn't exist and are not explicitly declared.
It sounds like you just want to break the text down into separate lines along the semicolons, add a dollar sign at the front and then add spaces and quotes. I'm not sure you can do that in one step with a regular expression (or at least I don't want to think about what that regular expression would look like), but you can do it over multiple steps.
Use preg_split() to split the string into an array along the
semicolons.
Loop over the array.
Use str_replace to replace each '=' with ' = "'.
Use string concatenation to add a $ to the front and a "; to the end of each string.
That should work, assuming your data doesn't include quotes, equal signs, semicolons, etc. within the data. If it does, you'll have to figure out the parsing rules for that.
I have a text string that is set in a variable to a value like these:
$str = 'type=showall'
or
$str = 'type=showall&skip=20'
$str = 'type=showall&skip=40'
$str = 'type=showall&skip=60'
and so on.
I need to check to see if there is a "skip" value present in the string, and if so replace it with a new number that is stored in a $newSkip variable and keep the string the same except for the change to the skip value.
For example if the string was:
$str = 'type=showall&skip=20'
and
$newSkip = 40
then I would like this to be returned:
$str = 'type=showall&skip=40'
If there was no skip value:
$str = 'type=showall'
and
$newSkip = 20
then I would like this to be returned:
$str = 'type=showall&skip=20'
I'm fairly new to PHP so still finding my way with the various functions and not sure which one/s are the best ones to use in this scenario when the text/value you're looking for may/may not be in the string.
PHP has a handy function called parse_str() which accepts a string similar to the one you have, and returns an array with key/value pairs. You'll then be able to inspect specific values and make the changes you need.
$str = 'type=showall&skip=20';
// this will parse the string and place the key/value pairs into $arr
parse_str($str,$arr);
// check if specific key exists
if (isset($arr['skip'])){
//if you need to know if it was there you can do stuff here
}
//set the newSkip value regardless
$arr['skip'] = $newSkip;
echo http_build_query($arr);
The http_build_query function will return the array into the same URI format that you started with. This function also encodes the final string so if you want to see the decoded version, you'll have to send it through urldecode().
References -
parse_str()
http_build_query()
I have strings like var=test;path=test.html
I want to convert these kind of strings like the array printed below :
Array
{
var => test
path => test.html,
}
I tried to use PHP's explode function for this task, but this is converting the string to associative array, and then i decided to convert that associate array to the one shown above.
But my own code isn't what i'm looking for, 'cause it contain 2 times PHP's explode function and some foreach loops, thus my own code will not stand in the department of performance for such a simple task.
Your help will be much appreciated, thanks.
Use parse_str for this:
http://www.php.net/manual/en/function.parse-str.php
You could explode by semicolon, then explode by =, and then use array_combine().
The solution is really not all that pretty, since it's quite verbose. I typed it out just in case, but you're probably better off with another method.
$s = "var=test;path=test.html";
$b = array_map(function($x){return explode("=", $x); }, explode(";", $s));
$c1 = array_map(function($x){return $x[0]; }, $b);
$c2 = array_map(function($x){return $x[1]; }, $b);
$result = array_combine($c1, $c2);
You could use preg_match_all to get an array of keys, and an array of values, then combine them into an associative array using array_combine:
$str = "var=test;path=test.html";
preg_match_all("/([^;=]+)=([^;=]+)/", $str, $matches);
$result = array_combine($matches[1], $matches[2]);
I just figured out how you can do that by using the parse_str php built-in function.
From the php.ini documentation:
; List of separator(s) used by PHP to parse input URLs into variables.
; PHP's default setting is "&".
; NOTE: Every character in this directive is considered as separator!
; http://php.net/arg-separator.input
; Example:
;arg_separator.input = ";&"
So, if you do this:
ini_set('arg_separator.input', ';&');
The parse_str should explode query arguments both on ; and &. This shouldn't affect in any way the filling of $_GET and $_POST since they are loaded before your code execution. If you want to be sure you don't affect the behavior of any other function calling parse_str, you could use a function like this:
function my_parse_str($str, &$arr) {
$orig = ini_get('arg_separator.input');
ini_set('arg_separator.input', ';');
parse_str($str, $arr);
ini_set('arg_separator.input', $orig);
}
Two advantages over exploding on & and then on =:
Maximum execution speed since the parse_str() function is built-in
parse_str() also considers recursive splitting: a=1&a=2 -> array('a'=>array('1', '2')); or 'a[one]=1&a[two]=2' -> array('a'=>array('one'=>'1', 'two'=>'2')).
Update - performance benchmarking
I just run a test to compare the plain-php splitting vs parse_str(), on an array of 10000 query strings each made of 500 arguments. The my_parse_str() above took ~0.952 seconds, while the pure-php one (parseQueryString()) took ~4.25 seconds.
It would require a larger set of data to test exactly how much it is faster, but it's pretty clear which one wins :) (if you want the test data + scripts, I'll upload them somewhere, since the data file is 125MB).
How about str_replace?
$text = "var=test;path=test.html";
$text = str_replace(';',"\n\t", $text);
$text = str_replace('='," => ", $text);
echo <<<END
Array
{
\t$text
}
END;
You'll need to do some extra work to get the proper formatting, though
i have a string with double quote like this
$count = 5;
$str = "result: $count";
echo $str; //result: 5
variable parsing work well, and my problem is $count var must be define later than $str
$str = "result: $count";
$count = 5;
echo $str; //result:
So i will use single quote and ask a question here to finding a way to parse var whenever i want
$str = 'result: $count';
$count = 5;
//TODO: parse var process
echo $str; //result: 5
I'm will not using regex replace.
For this type of thing, I'd probably use string formatting. In PHP, that'd be printf.
?php
$str="result: %d"
....dostuff.....define $count.....
printf($str,$count)
?
edit:
although, the best way to do this probably depends partly on why you have to define $string before $count.
If it's a string that's repeated a lot, and you wanted to put it in a global variable or something, printf would be my choice, or putting it in a function as other answers have suggested.
If the string is only used once or twice, are you sure you can't refactor the code to make $count be defined before $string?
finally, a bit of bland theory:
when you write '$string = "result: $count"',
PHP immediately takes the value of $count and puts it into the string. after that, it isn't worried about $count anymore, for purposes of $string, and even if $count changes, $string won't, because it contains a literal copy of the value.
There isn't, as far as I'm aware, a way of binding a position in a string to a yet-to-be-defined variable. The 'printf' method leaves placeholders in the string, which the function printf replaces with values when you decide what should go in the placeholders.
So, if you wanted to only write
$string = "result: $count"
$count=5
$echo string
(and not have to call another function)
and get
"result: 5",
there's no way to do that. The closest method would be using placeholders and printf, but that requires an explicit call to a function, not an implicit substitution.
Why don't you use a function?
function result_str($count) { return "result: $count"; }
preg_replace is the simplest method. Something like this:
$str = preg_replace("/\\$([a-z0-9_]+)/ie", "$\\1", $str);
But if you really don't want to use a regex, then you'll have to parse the string manually, extract the variable name, and replace it.