applying a random variable randomly - php

I have code generating a random font and applying a new random font to each line of text and would like to add a
$line = str_replace ("a", "#", $line);
But I would like the chance of this being applied to each line to be 10% rather than applied to the string as a whole. How can i do it? Here's my existing code:
$fonts = array("Helvetica", "Arial", "Courier", "Georgia", "Serif", "Comic Sans", "Tahoma", "Geneva", "Times New Roman");
shuffle($fonts);
$output = "";
$lines = array_slice(file("users.txt"), -20, 20);
$i = 0;
foreach ( $lines as $line ) {
if($i == count($fonts)) {
shuffle($fonts);
$i = 0;
}
$output .= '<div style="font-size: ' . rand(15, 23) . 'px; font-family:' . $fonts[$i] . '; margin-left: ' . rand(0, 60) . '%; opacity: 0.8;">' . $line . "</div>\n";
$i++;
}
echo $output;
I'm just starting to get familiar with php, I feel as though I've got a whole new web to play with! :D

If you'd like to have 10% chance of having your 'a' changed with '#' then try inserting this code:
if(rand(0, 9) == 1)
{
$line = str_replace ("a", "#", $line);
}
It generates an Integer from 0 - 9 and if it equals 1 (10% chance, then it applies your formatting.

so, in te foreach($lines as $line) loop, add this
$rand = rand(0,9);
if($rand == 0)
{
$line = str_replace("a","#",$line);
}

Related

Align sentences of a text file to left and right in PHP

$result = "";
while (some condition)
{
$result = file_get_contents("filename.txt");
$result = "$result\n" . $result;
file_put_contents("filename.txt", $result);
}
echo nl2br ($result);
I want to echo the first line as left aligned and second line as right aligned and so on on a web page. Is there any way to achieve this?
First you can split the text into an array buy using implode and use CSS to align them:
$result = "";
while (some condition){
$result = file_get_contents("filename.txt");
$result = "$result\n" . $result;
file_put_contents("filename.txt", $result);
}
$lines = implode('\n',$result);
echo "<div class='lines'>";
foreach($lines as $line){
echo $line;
}
echo "</div>";
// CSS:
echo '.lines > div:nth(even){ text-align:right; }';
$aLines = readfile(<file>);
for( $i = 0; $i < count( $aLines ); $i++ ) {
$align = ($i%2)?"left":"right";
echo "<div style='text-align: {$align}'>{$aLines[$i]}</div>";
}
Or if you meant to align inside the file itself:
$aLines = readfile(<source_file>);
$iLineWidth = 100;
$aLinesNew = [];
for( $i = 0; $i < count( $aLines ); $i++ ) {
$sLine = ($i%2)?$aLines[$i]:str_pad( $aLines[$i], $iLineWidth, " ", STR_PAD_LEFT);
$sLine = trim($sLine);
array_push( $aLinesNew, $sLine );
}
file_put_contents( <destination_file>, implode( "\n", $aLinesNew ) );

Coloring the echo output in php

I am reading a textile in php which has two sentences.
Top 1: 201 The Secret
Top 4 : 203, 290, 593, 224
What a Life!, Magical, Unicorn Land, Fire
function getcontent($file1){
$fh= fopen($file1, 'r');
$theData = fread($fh, filesize("$file1"));
return $theData;
fclose($fh);
}
?>
I wish to highlight the 2 sentences in different colors when I echo the file:
<div align="center"><h4 style="line-height:150%;"><?php echo "<pre>" .$movies. "</pre>"; ?></h5></div>
$movies is the textfile. How can I do so in php? Would I have to create a separate function for that?
PHP's file_get_contents function is a simpler way to get your file's contents.
If your file only ever has 2 lines, there may be a simpler way to do this, but you could split the lines via explode (for details on exploding text that might have strange line breaks, try here), which would look something like this:
$movies = file_get_contents("filename.txt");
$lines = explode("\n", $movies);
Then loop through the lines and style as desired:
if (is_array($lines)) {
$line_count = count($lines);
for ($i = 0; $i <= $line_count; $i++) {
if ($i % 2 == 0) {
echo '<span style="color: red;">' . $lines[$i] . '</span><br>';
}
else {
echo '<span style="color: blue;">' . $lines[$i] . '</span><br>';
}
}
}
More detailed logic could be implemented to color lines differently if there are more than 2 lines in the file.
Per your comment, the following code will color the first line red, and all other lines blue:
if (is_array($lines)) {
$line_count = count($lines);
for ($i = 0; $i <= $line_count; $i++) {
if ($i == 0) {
echo '<span style="color: red;">' . $lines[$i] . '</span><br>';
}
else {
echo '<span style="color: blue;">' . $lines[$i] . '</span><br>';
}
}
}
You could use an array to store the different sentences, so the new code would be something like this. By the way, code after a return statement is never executed, so avoid that
function getcontent($file1)
{
$lines = file($file); //read all lines to array
return $lines;
}
<div align="center">
<h4 style="line-height:150%;">
<?php
//lines is the array returned from getcontent
foreach($lines as $line)
{
echo "<pre>" .$line. "</pre>"
}
?>
</h5>
</div>
After that you could use an if-clause to swap colors so each row has an alternating color, or a random color if you'd like that

How to wrap words of string every 1000 characters in php

i have some big string, and some array of words that must be replaced with some changes, like wrapping in link. First issue is wrap whole words or combinations words. And the second issue is do previous step minimum every 1000 characters.
$string="lalala word lalala blah, blah lalala combination of words lalala lalala...";
$patterns=array('word','combination of words');
$replacements=array('word','combination of words');
For an example, what i must to do with snippet before?
It sounds to me like you're looking for wordwrap(). You can then use preg_replace_callback() to apply it to your search patterns and make the replacements:
foreach ($patterns as $pattern) {
$regex = '/' . preg_quote($pattern, '/') . '/';
$string = preg_replace_callback($regex, function($match) {
return '<a href="#">'
. wordwrap(htmlspecialchars($match), 1000, '<br />')
. '</a>';
}, $string);
}
SOLUTION:
<?php
function set_keys_by_words($content, $key, $words,$before,$after) {
$positions = array();
$string = '';
for ($i = 0; $i < count($words); $i++) {
$string = preg_replace('/\b' . $words[$i] . '\b/ui', $key . $words[$i], $content);
$position = mb_strpos($string, $key);
if ($position != '') {
$positions[(int) $position] = $words[$i];
}
}
ksort($positions);
$word = '';
$number = '';
$i = 0;
foreach ($positions as $k => $v) {
$i++;
if ($i == 1) {
$number = $k;
$word = $v;
}
}
if ((int) $number) {
$word_len = strlen($word);
$part_after = preg_replace('/\b' . $word . '\b/ui', $before . $word . $after, mb_substr($content, 0, $number + $word_len));
echo $part_after . mb_substr($content, $number + $word_len, 1000);
$content = mb_substr($content, $number + $word_len + 1000);
if ($content != '') {
set_keys_by_words($content, $key, $words);
}
} else if ($number == '' && $content != '') {
echo $content;
}
}
?>

apply different styles to different lines of text in PHP [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
How to get random value out of an array
I have code applying a random font to a div of text which is taken from the last 20 lines of a .txt file. I would like to apply a different random font to each line... any pointers?
<?php
$fonts = array("Helvetica", "Arial", "Courier", "Georgia", "Serif", "Comic Sans", "Tahoma");
shuffle($fonts);
$randomFont = array_shift($fonts);
$output = "";
$lines = array_slice(file("users.txt"), -20, 20);
foreach ( $lines as $line )
{
$output .= '<div style="font-family:' . $randomFont . '; margin-left: ' . rand(0, 60) . '%; opacity: 0.8;">' . $line . '</div>';
}
echo $output;
?>
Live demo here.
The code:
$fonts = array("Helvetica", "Arial", "Courier", "Georgia", "Serif", "Comic Sans", "Tahoma");
shuffle($fonts);
$output = "";
$lines = array();
for($i = 0; $i < 40; $i++) $lines[] = "line $i";
$i = 0;
foreach ( $lines as $line ) {
if($i == count($fonts)) {
shuffle($fonts);
$i = 0;
}
$output .= '<div style="font-family:' . $fonts[$i] . '; margin-left: ' . rand(0, 60) . '%; opacity: 0.8;">' . $line . "</div>\n";
$i++;
}
echo $output;
Randomize your fonts:
$Random = $fonts[rand(0, count($fonts) - 1)];
Been thinking about it and have a simpler solution.
<?php
$fonts = array ('font 1', 'font 2', 'font 3'); // 20 entries for the full set
shuffle ($fonts);
while ($font = array_pop ($fonts))
{
$output .= '<div style="font-family:' . $font . ';"></div>';
}
?>
This is obviously not an exact solution to the problem you posted above, and it's not intended to be. It's intended to provide an example of an approach for getting random values that are guaranteed to be unique. You should be able to incorporate the idea expressed here into your own code without too much difficulty.

PHP Foreach Loop and DOMNodeList

I am trying to determine the end of a foreach loop that is seeded with a collection of DOMNodeList. Currently, I am using a for loop would like to avoid having a 'magic' number there. I do know there are only going to be 8 columns, but I would like the code me generic for other applications.
Is it possible to convert this to a Foreach loop? I have tried the end() and next() functions, but they are not returning any data and I suspect that they only work on arrays and not this DOMNodeList collection.
The code is building a CSV file without the trailing ','
Current output is:
"Value 1","Value 2","Value 3","Value 4","Value 5","Value 6","Value 7","Value 8"
Here is an example of code:
$cols = $row->getElementsByTagName("td");
$printData = true;
// Throw away the header row
if ($isFirst && $printData) {
$isFirst = false;
continue;
}
for ($i = 0; $i <= 8; $i++) {
$output = iconv("UTF-8", "ASCII//IGNORE", $cols->item($i)->nodeValue);
$output2 = trim($output);
if ($i == 8) {
// Last Column
echo "\"" . $output2 . "\"" . "\n";
} else {
echo "\"" . $output2 . "\"" . ",";
}
}
You can use:
$cols->length
To retrieve the number of items in a DOMNodeList.
See http://php.net/manual/en/class.domnodelist.php
Edit:
If you change you're code to this, you don't have to worry about the trailing comma, or the length:
$output = array();
foreach ($cols as $item) {
$output = iconv("UTF-8", "ASCII//IGNORE", $item->nodeValue);
$output2 = trim($output);
$output[] = '"' . $output2 . '"';
}
$outputstring = implode(',', $output);
$cols->length
Should give you the number of items in the list
for ($i = 0; $i < $cols->length; $i++) {
// ...
if ($i == $cols->length - 1) {
// last column

Categories