Ok guys, this question is related to my previous one.
If I have set $textlimit = 500; that will limit my text to 500 characters.
Is there any way to "avoid" text limit, and then onclick function load rest of it?
For example, if I set:
$textpart = substr($fulltext, 0, 400);
$textpart will only contain 400 characters of string.
My question is, how to declare variable, which will contain the rest of the text which is much longer than 500 characters?
Example of variables:
$fulltext //Contains full text, but is limited to 500 characters.
$textpart //Contains part of the text, substr 400 characters out of 500.
$textrest //This variable to "hold" rest of the text, after 400 characters of $textpart.
Like I've asked in previous question, I wanted to make expand and collapse button, I now know how to do that, but I don't know how to divide text.
Form would go like this:
Random text here(400 characters long)
Random image for expand
After declared onclick function I, load rest of the text (Over 500 characters).
Random image for collapse
After declared onclick function collapse and return to previous state - citation 1.
I hope I explained my question the right way. I would really appreciate any kind of help, if I can choose, I would like just basic explanation on how to that, because I want to learn that, not copy/paste solution (it is easier, but I will not learn much).
Thanks in advance.
$textrest = substr($fulltext, 400)
$fulltext = substr($fulltext, 0, 500);
$textpart = substr($fulltext, 0, 400);
$textrest = substr($fulltext,400,strlen ( $fulltext ));
If I understand you correctly you want to show the user an initial page that shows only the first X characters and then show all the characters when the users clicks on the text.
There are three strategies to do this. From easy to hard:
Output the shortened text and include a link that will reload the whole page but with the whole text
Output all the text and use css and JavaScript to hide/show any overflow
Output the shortened text and perform an Ajax call to load the extra characters and append
Options 2 and 3 require the use of client side JavaScript and are therefore not pure PHP solutions.
Option 1 is a matter of adding a $_GET variable, e.g. ?expand=para1, to your url and expanding the text identified in PHP by $_GET['expand'].
Do not make the mistake of thinking PHP is still running on the page in the browser. Only JavaScript can run in the browser on the web page. (Not strictly true I know, but true enough in reality.)
Related
OK, so I shave my head, but if I had hair I wouldn't need a razor because I'd have torn it all out tonight. It's gone 3am and what looked like a simple solution at 00:30 has become far from it.
Please see the code extract below..
$psusername = substr($list[$count],16);
if ($psusername == $psu_value){
$answer = "YES";
}
else {
$answer = "NO";
}
$psusername holds the value "normann" which is taken from a URL in a text based file (url.db)
$psu_value also holds the value "normann" which is retrieved from a cookie set on the user's computer (or a parameter in the browser address bar - URL).
However, and I'm sure you can guess my problem, the variable $answer contains "NO" from the test above.
All the PHP I know I've picked up from Google searches and you guys here, so I'm no expert, which is perhaps evident.
Maybe this is a schoolboy error, but I cannot figure out what I'm doing wrong. My assumption is that the data types differ. Ultimately, I want to compare the two variables and have a TRUE result when they contain the same information (i.e normann = normann).
So if you very clever fellows can point out why two variables echo what appears to be the same information but are in fact different, it'd be a very useful lesson for me and make my users very happy.
Do they echo the same thing when you do:
echo gettype($psusername) . '\n' . gettype($psu_value);
Since i can't see what data is stored in the array $list (and the index $count), I cannot suggest a full solution to yuor problem.
But i can suggest you to insert this code right before the if statement:
var_dump($psusername);
var_dump($psu_value);
and see why the two variables are not identical.
The var_dump function will output the content stored in the variable and the type (string, integer, array ec..), so you will figure out why the if statement is returning false
Since it looks like you have non-printable characters in your string, you can strip them out before the comparison. This will remove whatever is not printable in your character set:
$psusername = preg_replace("/[[:^print:]]/", "", $psusername);
0D 0A is a new line. The first is the carriage return (CR) character and the second is the new line (NL) character. They are also known as \r and \n.
You can just trim it off using trim().
$psusername = trim($psusername);
Or if it only occurs at the end of the string then rtrim() would do the job:
$psusername = rtrim($psusername);
If you are getting the values from the file using file() then you can pass FILE_IGNORE_NEW_LINES as the second argument, and that will remove the new line:
$contents = file('url.db', FILE_IGNORE_NEW_LINES);
I just want to thank all who responded. I realised after viewing my logfile the outputs in HEX format that it was the carriage return values causing the variables to mismatch and a I mentioned was able to resolve (trim) with the following code..
$psusername = preg_replace("/[^[:alnum:]]/u", '', $psusername);
I also know that the system within which the profiles and usernames are created allow both upper and lower case values to match, so I took the precaution of building that functionality into my code as an added measure of completeness.
And I'm happy to say, the code functions perfectly now.
Once again, thanks for your responses and suggestions.
The following script has been created to test if the value of a db field has changed and if so then reload the page and if not, alert the user that the change has not happened.
The alert is just to see what is being returned by the .post function.
The auto_refresh works fine as i need it to check every 5 seconds, when the if() condition is set to '==' the page alert shows and if it is set to '!=' the page continually reloads.
jQuery.post is getting the db field data but it doesn't seem to be able to compare the 2 values correctly.
any help would be greatly appreciated, thanks
var auto_refresh = setInterval(function(){
$.post("/index.php/listen", function(data) {
if($('#slide').html() != data)
{
window.location.reload()
}
else
{
alert('its the same'+ data);
}
});
}, 5000);
EDITED
Rather than trying to parse raw data, why not pass HTML from the $.post() like:
<p>4</p>
Then the jQuery inserts the the replaces the p tag with the new version from the $.post()
because the html is passed on there is no white space and the comparison can be made correctly.
I don't think it is very safe to compare the new value with an html. Some browsers might add spaces or unwanted chars. I'd try to save the old value in an input of type hidden and use the .val() or, event better, in a variable. It depends of your scenario.
If $('#slide').html() == data
then that means that the conditional failed, it was not equal, so it showed the alert.
The problem is that the data variable might come back with a few extra white spaces. If I were you, I'd try to parse a small section of the data variable, and a small section of the html in slider and compare those values.
Like if slider has something within a p tag or an input value, compare it to the data to see if it has that same value returned in that p tag or input value, then replace all the whitespaces with an empty string just to be safe.
Btw, try not to use alerts since you can't really know for sure if there is an extra whitespace. Try to use something like "debugger" if using IE with visual studios, or console.log when using chrome or firefox.
You are comparing two html strings: one is serialized from the DOM, and another is from a server response.
There's no guarantee that the two strings will ever be the same! Think about it: the same rendered html can have many string differences. E.g. click and click are both the same HTML, but different strings.
You can take two different approaches here:
You can create some kind of canonicalization routine that guarantees that two html fragments you consider "the same" will have the same string form. Run both html fragments through this routine, then compare.
You can manage versions more explicitly.
Include some kind of version indicator:
You can use the ETAG header (which means you can take advantage of http caching mechanisms).
You can include some kind of version number in the html itself (maybe in a data-version attribute), and compare those.
You can keep the html string from your server separately and compare against that.
Below is a preview of what I am dealing with:
The heading, the text, and the image is all dynamically created based on the user. They can choose if they want to add a picture, and they can choose what text to put in the heading and the main content.
There cannot be any scrolling, so it has to be visible and cannot go past the bottom of that white.
My question is... how can I limit the text of the body?
If the heading is large and goes down to two lines, and there is a picture, then in order to stay in the lines and not go past the white it has to be limited to a certain amount of characters.
But another user could decide to not have a picture and keep the heading in one line, so that user will have more text to write so the limit should be different.
I guess the confusing part for me is like.. what if a user has no picture and has a short heading, and creates some really long text to fit the size, but then later on decides to add an image.. then that long text will now no longer fit. So now.. I can't limit the text because it's already there.
I hope that makes sense. If anyone could help me through this and give me some ideas I would really appreciate it.
Use this for whatever the user input is for adding text. It could limit the characters they use just change the 250 value.
<script>
function countChar(val){
var len = val.value.length;
if (len >= 250) {
val.value = val.value.substring(0, 250);
}else {
$('#charNum').text(250 - len);
}
};
</script
<textarea id="field" name="description" onKeyUp="countChar(this)"></textarea>
its not only the text you need to limit but also the image thumbnail so that affect the style of your webpage
To limit the number of string .. i would you use a script form here php trim a string
function trim_word($str, $length, $suffix = '...')
{
$len = strlen($str);
if ($len < $length) return $str;
$pattern = sprintf('/^(.{%d,}?)\b.*$/', $length);
$str = preg_replace($pattern, '$1', $str);
$str = trim($str);
$str .= $suffix;
return $str;
}
it trim the text and makes sure it always ends with a word ...
You can use http://phpthumb.sourceforge.net/ to generate thumbnail of fixed size all you need to do it set your desired height and width
There are a few different options to consider. You may want to limit the amount of text the user can enter for starters, to ensure it doesn't overflow.
One thing I would probably do is find the maximum amount of characters you're comfortable with on the page, and use substr on the output from the database to ensure that it never displays more.
http://php.net/manual/en/function.substr.php
You could have a "more" link that way the visitor could read more if they want, but it doesn't break the layout. I would use basic if statements for the logic (if picture exists, trim text to this, if not etc).
Hope that helps.
Surround the entire thing with a container div of the fixed height which you desire with no padding, and inside that place another inner div with no margin and no fixed height, then as the user changes the content create a javascript function to check if the inner div is < the container div; and if not then do not allow the user to make that change - this way you are attacking the problem directly.
<script>
function checkDivs() {
if(inner.style.height >= container.style.height) {
//prevent change
}
}
</script>
<div id='container'>
<div id='inner'>
//User-defined content
</div>
</div>
This function would be attached to whatever GUI the user would edit the content through, as for how to prevent the change, I'd have to know more about your program.
I want a phone number which display on public page will be protected. Example converts phone number characters to HTML entities and bots can't grab the number in plain text. Let me know the trick.
This is a...passing thought, though I'm not sure how practical it would be:
<span class="protectedNumber" title="01234567890"></span>
css:
span.protectedNumber:before {
content: "Phone number: " attr(title);
}
JS Fiddle demo.
Edited, in response to 'cross browser?' question in comments, to add a jQuery option to assist with those browsers that don't have the ability to deal with css-generated content:
$(document).ready(
function(){
$('.protectedNumber').each(
function(){
$(this).text('Phone number: ' + $(this).attr('title'));
});
});
some ideas
display the phone number as an image
use javascript to create and display the phone number
throw in html tags in between the numbers (e.g. [span]) that visually makes no difference but makes it more difficult for the bot to recognize the phone number
Try writing the number using ASCII:
http://www.ascii.cl/htmlcodes.htm
<html>
<body>112</body>
</html>
The first thing I'd think of is render an image.
Use Javascript to obfuscate
Obfuscate using a php function
Sure just print the phone number using words instead of numbers...
Create an image of the number, this will foil MOST bots, but some may have OCR, so obfuscate it.
ie: Good:
Better:
The 2nd 1 better because like Captcha, the background contains "noise" that makes it hard for OCR enabled bots to harvest, but is as readable to human eyes..
The hard solution would be use Captcha or a simple PHP script to create the picture on the fly, but in most cases, unless you using alot of different #'s the "better" solution above easiest and quickest method, can do easy even in simple program like Paint in 5 min.
For the visually impaired, include a small link to an audio file (mp3) of you saying the number, if it linked properly, and accordingly, it should work.
I'm writing code to generate character-based pagination. I have articles in my site that I want to split up based on length.
The code I have so far is working albeit two issues:
It's splitting pages in the middle of words and HTML tags; I want it to
only split after a complete word, tag, or a punctuation mark.
In the pagination bar, it's generating the wrong number of pages.
In the
pagination bar, it's generating the
wrong number of pages.
Need help addressing these two issues. Code follows:
$text = file_get_contents($View);
$ArticleLength = strlen($text);
$CharsPerPage = 5000;
$NoOfPages = round((double)$ArticleLength / (double)$CharsPerPage);
$CurrentPage = $this->ReturnNeededObject('pagenumber');
$Page = (isset($CurrentPage) && '' !== $CurrentPage) ? $CurrentPage : '1';
$PageText = substr($text, $CharsPerPage*($Page-1), $CharsPerPage);
echo $PageText, '<p>';
for ($i=1; $i<$NoOfPages+1; $i++)
{
if ($i == $CurrentPage)
{
echo '<strong>', $i, '</strong>';
}
else
{
echo '', $i, '';
}
echo ' | ';
}
echo '</p>';
What am I doing wrong?
Thanks, guys. I put in the fix for the 1st point and it worked beautifully.
Hm. I guess it is messy to do the second point. I've found some regex on-line. Will think, write, and get back to you when I make some progress.
Thanks again.
$NoOfPages = round((double)$ArticleLength / (double)$CharsPerPage);
That should use ceil instead of round - if you use round, 4.2 pages will only show 1-4 - you need a 5th page to show the last .2 of a page.
The other part is harder ... its common to use some sort of marker in the file to indicate where the page breaks go as no matter how clever your code, it can't appreciate where is a good break in then same way a human can.
If you insist on doing it suggest some logic that first works forwards/backwards to the nearest space when a page break is created, which isn't too tricky. More tricky is deciding when you are within a tag or not .... think you'll either need some fairly heavy regex, or else an HTML parsing tool.
You're calculating the number of pages wrong... you should be using ceil() not round() (for example 4.1 pages worth of text is still 5 pages to display).
To fix the other issue, you're going to have big problems if there's arbitrary HTML in there. For example, you need to know that <div>s and <p>s are OK to split, but <table>s aren't (unless you want to get really fancy)!
To do it properly you should use an HTML library to build a tree of elements and then go from there.
Based on your first statement,
It's splitting pages in the middle of words and HTML tags
it appears that your character count is being done after markup is inserted. That would imply that e.g. long URLs in links would be counted against the page length you're trying to achieve. However, you didn't say how the articles were being created initially.
I'd suggest looking for a point in the process of creating the article where you could examine the raw text. By regarding the actual content (without markup) as a set of paragraphs, and estimating the vertical length of each paragraph based on typical number of characters per line, you can come up with a more consistent sizing.
I would also consider only breaking between paragraphs, to keep units of thought together on the same page. Speaking as a reader, I really hate going to sites that force me to pause, hit a button or link, and wait for a page reload, all in the middle of a single thought.