PHP echo name+var - php

I basically have to create a website that display 3 random items out of a total of 10. I have named each of them $item# (# being a number 1-10) and I'm trying to display them using echo.
This is how I have the content stored
$item1 = '<img src="Images/coffee1.png" class="imgLeft" />
<h3>Title 1</h3>
<p>
L.
</p>';
I used this to create a variable with a random int between 1-10
$f1 = rand(1, 10);
And I'm trying to display it using this
<?php echo $item; ?>
If I put a number after item it works perfectly, but I can't figure out how to put $f1 instead.
Thank you

First of all you have to declare your random number before inserting into your Item. if you do it after then your Item doesn't reconize it.
Then in php we can use a concatenation of vars like $f1 . $f2 and it the same when we use it with String type so your Item is a String concatenated with an Integer but we want it inside the string.
In conclusion we have to concatenate String like this `
"Your String ".$1."The rest of String"; OR 'Your String '.$1.'The rest of String';
`
$f1 = rand(1, 10);
$item1 = '<img src="Images/coffee'. $f1 .'.png" class="imgLeft" />
<h3>Title '. $f1 .'</h3>
<p>L.</p>';
<?php echo $item; ?>

Here is how it will work...
$f1 = rand(1, 10);
$$f1 = '<img src="Images/coffee'. $f1 .'.png" class="imgLeft" />
<h3>Title '. $f1 .'</h3>
<p>
L.
</p>';
echo $$f1;

My last edited Answer Now:
It is working...
$f1 = rand(1, 10);
$item = '';
$ite = $item.$f1;
$ite = '<img src="images/'.$f1.'.png" class="imgLeft" /><h3>Title '. $f1 .'</h3><p>L.</p>';
echo $ite;

Related

extract pure text strings from php scripts for translation

I have project which contains bigger amount of php files. Former programmer wrote everything (texts) in english in source files together with html code and I need to make translation now. Go manually file by file and extract all texts to one lanugage file is huge pain. Is there any free tool please to extract and convert all text to e.g. variables in source files and produce just one big file with text variables to simple translation?
many thanks.
P.S. I would like to automatize this work rather than manually do it file-by-file.
Examples of code in php files:
<?php
echo "Hi back, " . $user;
?>
<center class="title">No list(s) available.</center>
<tr id="exp<?php echo $r; ?>" class="me" onmouseover="dis('<?php echo $u; ?>');"> <td>This is new statement</td></tr>
this function is gonna help you in some cases and it returns the plain text between > and <
before you start you need to replace
' (quotation)
with
\' (backslash quotation)
$text = '
<?php
echo "Hi back, " . $user;
?>
<center class="title">No list(s) available.</center>
<tr id="exp<?php echo $r; ?>" class="me" onmouseover="dis(\'<?php echo $u; ?>\');"> <td>This is new statement</td></tr>
';
the function is:
function getSentences($string){
$arr = array();
$parts = explode(">", $string);
if(count($parts) > 2){
$pattern = "/\>(.*?)</";
foreach($parts as $part){
$part = ">" . $part;
preg_match($pattern, trim($part), $matches);
if(!empty($matches[1]) AND $matches[1] != " "){
if(preg_match('/^[a-zA-Z0-9]/', $matches[1])){
$arr[] = $matches[1];
}
}
}
}else{
$pattern = "/\>(.*?)</";
preg_match($pattern, $string, $matches);
$arr[] = $matches[1];
}
return $arr;
}
and call the function by :
print_r(getSentences($text));
the output will be something like this:
Array ( [0] => No list(s) available. [1] => This is new statement )

PHP regex replace with diffrent action for each result

In PHP I'm trying to replace all iframe tags with paragraph tag that include the ifame tag.
in other words im trying to surround the iframe tag with <p> tag that have a random number.
everything is working fine except when $record contains more than one iframe tag, in that case it would give the same paragraph number for the all the <p> tags.
here is my code:
$x = rand(1, 99);
$replacement = '<p' . $x . '>$1</p' . $x . '><br>';
$record = preg_replace("/(<iframe.*<\/iframe>)/U", $replacement, $record);
i want to give a unique number for for the tag for each iframe tag
ex:
<p1><iframe>sometext</iframe></p1>
<p2><iframe>sometext</iframe></p2>
$s = <<<'HTML'
<p1><iframe>sometext1</iframe></p1>
<p2><iframe>sometext2</iframe></p2>
HTML;
$re = "/(<iframe[^>]*>.*?<\/iframe>)/U";
echo preg_replace_callback($re, function ($a) {
$x = rand(1, 99);
return '<p' . $x . '>'.$a[1].'</p' . $x . '><br>';
}, $s);

How to store an array?

I need help about an exercise. It says I have to create a little program in PHP which creates 7 random numbers (actually it's a lottery with 6 random numbers and 1 random number (complementary) between 1 and 49). That numbers have to store in an array.
The problem is I must to store that numbers in a file too. I did this:
$num[1]=rand(1,49);
$num[2]=rand(1,49);
$num[3]=rand(1,49);
$num[4]=rand(1,49);
$num[5]=rand(1,49);
$num[6]=rand(1,49);
$num[7]=rand(1,49);
echo "The numbers are: "; echo $num[1]; echo "-"; echo $num[2]; echo "-"; echo $num[3]; echo "-"; echo $num[4]; echo "-"; echo $num[5]; echo "-"; echo $num[6];
echo "<br>";
echo "Complementary: ".$num[7];
Then I tried something like this to store that numbers:
$lott=array($num[1],$num[2],$num[3],$num[4],$num[5],$num[6]);
$comp=array($num[7]);
$arch=fopen("lottery.txt","a") or die("Internal error");
fputs($arch,"Lottery numbers:");
fputs($arch,$_REQUEST['lott']);
fputs($arch,"\n");
fputs($arch,"\n");
fputs($arch, "Complementary number:");
fputs($arch,$_REQUEST['comp']);
fputs($arch,"\n");
fputs($arch,"-------------------------------------------------------");
fputs($arch,"\n");
fclose($arch);
echo "The dates have been stored correctly.";
Obviously it doesn't work. I'm new with php, so I don't know how to store that numbers in a file.
I appreciate the help.
You are trying to save $_REQUEST['lott'] and $_REQUEST['comp'] to your file. Are these variables set?
Just save your $lott and $comp variables. Both are arrays and therefor must be converted to string, before you can save it. You can use implode() for this.
$lott=array($num[1],$num[2],$num[3],$num[4],$num[5],$num[6]);
$comp=array($num[7]);
$arch=fopen("lottery.txt","a") or die("Internal error");
fputs($arch,"Lottery numbers:");
fputs($arch,implode(',', $lott));
fputs($arch,"\n");
fputs($arch,"\n");
fputs($arch, "Complementary number:");
fputs($arch,implode(',', $comp));
fputs($arch,"\n");
fputs($arch,"-------------------------------------------------------");
fputs($arch,"\n");
fclose($arch);
This will output
Lottery numbers:37,27,41,1,2,14
Complementary number:19
-------------------------------------------------------
You can use function implode to join your array data in one string:
$lott=array($num[1],$num[2],$num[3],$num[4],$num[5],$num[6]);
$comp=array($num[7]);
$arch=fopen("lottery.txt","a") or die("Internal error");
fputs($arch,"Lottery numbers:");
fputs($arch, implode(' - ', $lott); //HERE
fputs($arch,"\n");
fputs($arch,"\n");
fputs($arch, "Complementary number:");
fputs($arch,$comp[0]); //HERE you get only index 0, because your array have just one item
fputs($arch,"\n");
fputs($arch,"-------------------------------------------------------");
fputs($arch,"\n");
fclose($arch);
echo "The dates have been stored correctly.";
Here is to your answer: The code is commented though---
<?php
// GENERATE 6 RANDOM NUMBERS BETWEEN 1 AND 49 WITH...
$arrRandNumbers = array();
for($i=1; $i<7; $i++){
$arrRandNumbers[] = rand(1, 49);
}
// BUILD-UP A STRING FOR THE RANDOM NUMBERS, DELIMITED WITH A NEW LINE CHARACTER
$strRandom = "";
foreach($arrRandNumbers as $randNumber){
$strRandom .= $randNumber . "\n";
}
// STORE NUMBER IN A TEXT FILE... FILE-NAME: random-numbers.txt
file_put_contents("random-numbers.txt", rtrim($strRandom, "\n"));
var_dump($arrRandNumbers);
And here is another Variant:
<?php
// GENERATE 6 RANDOM NUMBERS BETWEEN 1 AND 49 WITH...
$arrRandNumbers = array();
for($i=1; $i<7; $i++){
$arrRandNumbers[] = rand(1, 49);
}
// GENERATE A COMPLEMENTARY NUMBER: BETWEEN 1 AND 49 WITH...
$compNum = rand(1, 49);
// BUILD-UP A STRING FOR THE RANDOM NUMBERS, DELIMITED WITH 2 SPACES & WRAPPED IN SQUARE BRACKETS
$strRandom = "LOTTERY NUMBERS:" .PHP_EOL;
foreach($arrRandNumbers as $randNumber){
$strRandom .= "[" . $randNumber . "] ";
}
// TRIM-OFF THE SPACES TO THE RIGHT OF THE LOTTERY NUMBERS:
rtrim($strRandom);
// ADD THE COMPLEMENTARY NUMBER TO THE MIX WITH 3 NEW LINES IN-BETWEEN:
$strRandom .= "\n\n\nCOMPLEMENTARY NUMBER:\n" . $compNum;
// STORE NUMBER IN A TEXT FILE... FILE-NAME: random-numbers.txt
file_put_contents("random-numbers.txt", $strRandom);
var_dump($arrRandNumbers);
<?php
$num[1]=rand(1,49);
$num[2]=rand(1,49);
$num[3]=rand(1,49);
$num[4]=rand(1,49);
$num[5]=rand(1,49);
$num[6]=rand(1,49);
$num[7]=rand(1,49);
echo "The numbers are: "; echo $num[1]; echo "-"; echo $num[2]; echo "-"; echo $num[3]; echo "-"; echo $num[4]; echo "-"; echo $num[5]; echo "-"; echo $num[6];
echo "<br>";
echo "Complementary: ".$num[7];
$lott=array($num[1],$num[2],$num[3],$num[4],$num[5],$num[6]);
$comp=array($num[7]); // You don't need an array to store only one number
$arch=fopen("lottery.txt","a") or die("Internal error");
fputs($arch,"Lottery numbers:");
//fputs($arch,$_REQUEST['lott']);
foreach ($lott as $number)
{
fputs($arch, $number);
fputs($arch, "\n");
}
fputs($arch, "Complementary number:");
//fputs($arch,$_REQUEST['comp']);
fputs($arch, $comp[0]);
fputs($arch,"\n");
fputs($arch,"-------------------------------------------------------");
fputs($arch,"\n");
fclose($arch);
echo "The dates have been stored correctly.";

Generating a list from a text file in PHP

I am attempting to create an ordered list from a text file. As my code currently stands, it modifys the original text file with the input all on the same line(list number). e.g if I input "mercury" it will come out as 1. mercury, but if I input "venus", it will appear as 1.mercuryvenus
I am trying to get it to work so that if I input some text such as "mercury" and hit the submit button, it will appear as
1. mercury. If I input some more text such as "venus", it will appear as 2. venus, all in ordered list format. I assume that explode may be used for this, but I am unsure of how to implement this properly. Another option would be to create a new text file for each input if that were to be more efficient.
echo "<form method='post'>
<label>Enter some text</label><br>
<textarea name='textbox' cols='60' rows='5' required></textarea>
<br>
<input type='submit' name='submit' value='Submit'/>
<input type='hidden' name='step' value=''/>
</form>";
echo "<section>";
echo "<h3>Current tasks</h3>";
$text = ("text.txt");
$extract = (isset($_POST['textbox']) ? $_POST['textbox'] : null);
$file = fopen($text,"a");
fwrite($file,$extract);
fread($file,filesize("text.txt"));
fclose($file); #Not sure where this should really go
$c = array(file_get_contents('text.txt'));
$x = explode(" ",$c); #Could be wrong format
echo "<ol>";
foreach($c as $r) {
echo "<li>" . $r. "</li>", "<br>";
}
echo "</ol>";
echo "</section>";
Here is the solution
echo "<section>";
echo "<h3>Current tasks</h3>";
$text = "text.txt";
$extract = (isset($_POST['textbox']) ? $_POST['textbox'] : null);
$file = fopen($text,"a+");
fwrite($file," ".$extract);
#fread($file,filesize("$text"));
$x = explode(" ",file_get_contents($text));
if(isset($_POST['submit'])) {
echo "<ol>";
foreach ($x as $r) {
echo "<li>" . $r . "</li>", "<br>";
}
echo "</ol>";
echo "</section>"
First, the "a" in fopen($text,"a") means append. Which means if you already have the text "mercury" in your file and your run your program again with "venus", you will be appending "venus" on the end of "mercury" to get "mercuryvenus". If you want a space between the two, you will have to add it when your write it to file: fwrite($file, " ".$extract);
Second, you do $x = explode(... and then do not use $x in your foreach statement. Use $x instead of $c in your foreach.

while-loops and if-statement trouble php

I want to be able to check wheter an inputted string has any of the characters in $alphabet and if it does display the relevant image per relevant character. so if someone entered hello. it would display h.png, e.png, l.png, l.png and o.png. So far I have got it to recognise the users input and echo it out and search whether it has a particular letter and output it to the relevant image via this code:
<?php
$input = trim($_POST["textarea"]);
echo $input;
echo "<br />";
if(strcmp($input[0],'a')==0){
echo "<img src='egypt/$input.png'>";
}else{
echo "You did not write a";
}
?>
Which works perfectly. However I tried to input more code which would allow a whole string including spaces to be analysed against the whole alphabet $alphabet and match each character in the string to the right image with this code below: but it doesnt work
<?php
$input = trim($_POST["textarea"]);
echo $input;
echo "<br />";
$alphabet = array('a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z');
while (list(, $value) = each($alphabet) AND list(, $input) = each($value2)) {
if(strcmp($value2[0],$value)==0){
echo "<img src='egypt/$value2.png'>";
}else{
echo "You did not write a";
}
}
?>
Above is the neccessary code.
Update: I have worked out how to match the first letter of input against any in the alphabet but still struggling to work out how to map against a whole string with spaces.
<?php
$input = trim($_POST["textarea"]);
echo $input;
echo "<br />";
$alphabet = array('a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z');
if(strcmp($input[0],$alphabet)==0){
echo "<img src='egypt/$input.png'>";
}else{
echo "Error";
}
?>
Code with reference to update for anyone who cares
Let me suggest you a different route.
$fos='hello world!';
$cucc=preg_replace('/([a-z])/', '<img src="$1.png" />', $fos);
This will replace every letter (a-z) with its img equivalent, so you will get this result:
<img src="h.png" /><img src="e.png" /><img src="l.png" /><img src="l.png" /><img src="o.png" /> <img src="w.png" /><img src="o.png" /><img src="r.png" /><img src="l.png" /><img src="d.png" />!
I'm not sure if this will solve your problem completely, but I noticed this right away:
while (list(, $value) = each($alphabet) AND list(, $input) = each($value2))
should be:
while (list(, $value) = each($alphabet) AND list(, $value2) = each($input))

Categories