I want to add 300 spaces to a text file with PHP. I can't use   as you already knew (.txt format, not HTML), so how to do this?
So this code counts numbers as you can see, I need 300 white-spaces.
$spaces = 0; // will become 300 spaces
while ($spaces < 300)
{
$spaces++;
}
and for testing how many white-spaces I have I will use
substr_count($spaces, ' ');
Thanks
Instead of creating a loop to build them, just use the following
$padded_text = str_pad($some_text, 300, ' ', STR_PAD_LEFT);
Anything less than 300 chars big, gets spaces added, and depending where you want those spaces, you can try using STR_PAD_RIGHT or STR_PAD_BOTH. And if you have no characters at all, it will generate it full of 300 spaces, this will be faster than using a loop.
Now if you simply want to add 300 spaces (not pad it so that there will be less than 300 spaces) you'll want to use
$spaces = str_repeat(' ', 300);
Related
I have a bunch of file. I need to print out the file only ITEM_DESCRIPTION: part. Lets say the contents of each files is like below
// ITEM_DESCRIPTION: Phone 1
// - Android 9.0 (Pie)
// - 64/128 GB
// - Li-Po 3500 mAh
I want the code to display like below
Phone 1
- Android 9.0 (Pie)
- 64/128 GB
- Li-Po 3500 mAh
so far, what I can produce is
// Phone 1 // - Android 9.0 (Pie) // - 64/128 GB // - Li-Po 3500 mAh
How I want to separate the double slash with new line?
Here is my code
// Get file path
// This code inside for loop which i don't write here
$filedir=$filelist[$i];
//Display Item Description
$search = "ITEM_DESCRIPTION";
$endsearch = "BRAND";
$contents = stristr(file_get_contents($filedir), $search);
$description = substr($contents, 0, stripos($contents, $endsearch));
$rmv_char = str_replace(str_split('\:'), ' ', $description);
$newline = str_replace(str_split('\//'), PHP_EOL , $rmv_char);
$phone_dscrpn = substr($newline, strlen($search));
Here is the way I had tried, but it doesn't work
$newline = str_replace(str_split('\//'), PHP_EOL , $rmv_char);
$newline = str_replace(str_split('\//'), "\r\n" , $rmv_char);
It looks like you already have newlines in the original data so you don't need to add them again. You just need to clear the slashes and the spaces (or tabs if that's what they are, hard to tell on SO).
Remember if you're testing output in browser it won't show the newlines without <pre></pre>.
// Get file path
// This code inside for loop which i don't write here
$filedir=$filelist[$i];
//Display Item Description
$search = "ITEM_DESCRIPTION";
$endsearch = "BRAND";
$contents = stristr(file_get_contents($filedir), $search);
$description = substr($contents, 0, stripos($contents, $endsearch));
//Clear out the slashes
$phone_dscrpn = str_replace("//", "", $description);
//Clear out the spaces
while(strpos($phone_dscrpn," ")!==false) {
$phone_dscrpn = str_replace(" ", " ", $phone_dscrpn);
}
Note this will replace any double slashes or double spaces within the description. If this could be an issue then you will need to consider a more advanced approach (e.g. line by line).
Assuming that all of your lines begin with // and this pattern isn't used in the actual product description then you can use a simple regular expression:
$description = preg_replace('~//\s(ITEM_DESCRIPTION:)?\s+~', '', $description);
Match //\s where \s is any white-space
Optionally match ITEM_DESCRIPTION:
Match \s+ any number of white-space characters
This will give you:
Phone 1
- Android 9.0 (Pie)
- 64/128 GB
- Li-Po 3500 mAh
I have the following output:
Item
Length : 130
Depth : 25
Total Area (sq cm): 3250
Wood Finish: Beech
Etc: etc
I want to remove the Total Area (sq cm): and the 4 digits after it from the string, currently I am trying to use str_replace like so:
$tidy_str = str_replace( $totalarea, "", $tidy_str);
Is this the correct function to use and if so how can I include the 4 random digits after this text? Please also note that this is not a set output so the string will change position within this.
You can practice php regex at http://www.phpliveregex.com/
<?php
$str = '
Item
Length : 130
Depth : 25
Total Area (sq cm): 3250
Wood Finish: Beech
Etc: etc
';
echo preg_replace("/Total Area \(sq cm\): [0-9]*\\n/", "", $str);
Item
Length : 130
Depth : 25
Wood Finish: Beech
Etc: etc
This will do it.
$exp = '/\(sq cm\): \d+/';
echo preg_replace($exp, '', $array);
Try with this:
preg_replace('/(Total Area \(sq cm\): )([0-9\.,]*)/' , '', $tidy_str);
You are looking for substr_replace:
$strToSearch = "Total Area (sq cm):";
$totalAreaIndex = strpos($tidy_str, $strToSearch);
echo substr_replace($tidy_str, '', $totalAreaIndex, strlen($strToSearch) + 5); // 5 = space plus 4 numbers.
If you want to remove the newline too, you should check if it's \n or \r\n. \n add one, \r\n add two to offset. Ie. strlen($strToSearch) + 7
How can i only echo 5 lines?
<?php
$text = Here i have a long long long text about 20 lines;
echo $text;
?>
So and i want something like that.->
TEXTLINE 1
TEXTLINE 2
TEXTLINE 3
TEXTLINE 4
TEXTLINE 5
And than stop.
Code for the mentioned text of Harri (at least this would be my approach):
$strings = explode(" ", $text);
for($i=0; $i<$your_lines; $i++) {
echo $strings[$i] . " ";
}
Explode the string to array, then loop through the array until last line you want to print. Printh each line while looping the array.
when you need lines (not words) use
$lines = explode(PHP_EOL, $text);
Assuming the output is a web browser, then this is a display issue, since what you are referring to as "line" depends on the width/height of the container. (It's not very clear what you try to ask)
You can set a width and height on a div using css and use overflow hidden on that to achieve a result like the one you want
demo
http://jsfiddle.net/g5Y5c/
.mydiv {width:100px;height:100px;overflow:hidden;}
I'm working in PHP and I want to create a function that, given a text of arbitrary length and height, returns a restricted version of the same text with a maximum of 500 characters and 10 lines.
This is what I have so far:
function preview($str)
{
$partialPreview = explode("\n", substr($str, 0, 500));
$partialPreviewHeight = count($partialPreview);
$finalPreview = "";
// if it has more than 10 lines
if ($partialPreviewHeight > 10) {
for ($i = 0; $i < 10; $i++) {
$finalPreview .= $partialPreview[$i];
}
} else {
$finalPreview = substr($str, 0, 500);
}
return $finalPreview;
}
I have two questions:
Is using \n proper to detect new line feeds? I know that some
systems use \n, other \r\n and others \r, but \n is the most
common.
Sometimes, if there's an HTML entity like " (quotation mark) at
the end, it's left as ", and therefore it's not valid HTML. How
can I prevent this?
First replace <br /> tags with <br />\n and </p><p> or </div><div> with </p>\n<p> and </div>\n<div> respectively.
Then use the PHP function for strip tags which should yield a nice plain text with newlines in everyplace a newline should be.
Then you could replace \r\n with \n for consistency. And only after that you could extract the desired length of text.
You may want to use word wrapping to achieve your 10 line goal. For word wraps to work you need to define a number of characters per line and word wraps takes care of not braking mid-word.
You may want to use the html_entity_decode before using wordwrap as #PeeHaa suggested.
Is using \n proper to detect new line feeds? I know that some systems use \n, other \r\n and others \r, but \n is the most common.
It depends where the data is coming from. Different operating systems have different line breaks.
Windows uses \r\n, *nix (including mac OS) uses \n, (very) old macs used \r. If the data is coming from the web (e.g. a textarea) it will (/ should) always be \r\n. Because that's what the spec states user agents should do.
Sometimes, if there's an HTML entity like " (quotation mark) at the end, it's left as ", and therefore it's not valid HTML. How can I prevent this?
Before cutting the text you may want to convert html entities back to normal text. By using either htmlspecialchars_decode() or html_entity_decode depending on your needs. Now you won't have the problem of breaking the entities (don't forget to encode it again if needed).
Another option would be to only break the text on whitespace characters rather than a hard character limit. This way you will only have whole words in your "summary".
I've created a class which should deal with most issues. As I already stated when the data is coming from a textarea it will always be \r\n, but to be able to parse other linebreaks I came up with something like the following (untested):
class Preview
{
protected $maxCharacters;
protected $maxLines;
protected $encoding;
protected $lineBreaks;
public function __construct($maxCharacters = 500, $maxLines = 10, $encoding = 'UTF-8', array $lineBreaks = array("\r\n", "\r", "\n"))
{
$this->maxCharacters = $maxCharacters;
$this->maxLines = $maxLines;
$this->encoding = $encoding;
$this->lineBreaks = $lineBreaks;
}
public function makePreview($text)
{
$text = $this->normalizeLinebreaks($text);
// this prevents the breaking of the "e; etc
$text = html_entity_decode($text, ENT_QUOTES, $this->encoding);
$text = $this->limitLines($text);
if (mb_strlen($text, $this->encoding) > $this->maxCharacters) {
$text = $this->limitCharacters($text);
}
return html_entity_decode($text, ENT_QUOTES, $this->encoding);
}
protected function normalizeLinebreaks($text)
{
return str_replace($lineBreaks, "\n", $text);
}
protected function limitLines($text)
{
$lines = explode("\n", $text);
$limitedLines = array_slice($lines, 0, $this->maxLines);
return implode("\n", $limitedLines);
}
protected function limitCharacters($text)
{
return substr($text, 0, $this->maxCharacters);
}
}
$preview = new Preview();
echo $preview->makePreview('Some text which will be turned into a preview.');
I've got text where some lines are indented with 4 spaces. I've been trying to write a regex which would find every line beginning with 4 spaces and put a <span class="indented"> at the beginning and a </span> at the end. I'm no good at regex yet, though, so it came to nothing. Is there a way to do it?
(I'm working in PHP, in case there's an option easier than regex).
Example:
Text text text
Indented text text text
More text text text
A bit more text text.
to:
Text text text
<span class="indented">Indented text text text</span>
More text text text
A bit more text text.
The following will match lines starting with at least 4 spaces or a tab character:
$str = preg_replace("/^(?: {4,}|\t *)(.*)$/m", "<span class=\"indented\">$1</span>", $str);
I had to do something similar, and one thing I might suggest is changing the goal formatting to be
<span class="tab"></span>Indented text text text
You can then set your css something like .tab {width:4em;} and instead of using preg_replace and regexes, you can do
str_replace($str, " ", "<span class='tab'></span>");
This has the benefit of allowing for 8 spaces to turn into a double width tab easily.
I think this should work:
//get each line as an item in an array
$array_of_lines = explode("\n", $your_string_of_lines);
foreach($array_of_lines as $line) {
// First four characters
$first_four = substr($line, 0, 4);
if($first_four == ' ') {
$line = trim($line);
$line = '<span class="indented">'.$line.'</span>';
}
$output[] = $line;
}
echo implode("\n",$output);