Shorten text to add read more link - php

I have the following HTML code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>TestPost</title>
<script src="jquery-2.1.4.min.js"></script>
<script src="more.js"></script>
</head>
<body>
<div class="post1">
This is post one
</div>
<div class="post1">
Another post number one
</div>
<div class="post2">
And this is post two
</div>
<div class="post3">
Last but not least, post three
</div>
</body>
</html>
What i'm looking for is the folowing:
When the text in a div is longer that, lets say, 5 chars, it should cut it off and add ...read more(including a link to a page).
I tried some PHP and some JQuery, but to be honest, I'm not sure anymore what to use.
If I could get the answer, that would be fantastic, but a push in the right direction would be very appreciated as well :)
Edit: The second post1 was added for testing purposes for anyone who's wondering.

Use attribute class instead of id. replace id='post' with class='post'
Use this code into your more.js
var mess_content = $('.post');
mess_content.each(function(){
if ($(this).text().length > 120) {
var obrtext = $(this).text().substr(0,120) ;
$(this).html(obrtext+"<a href='#'>read more</a>") ;
}
});

To do this with PHP, when you ouput your text, run it through a shortening function like this:
function shorten($output, $limit = 5) {
$output = htmlspecialchars($output, ENT_QUOTES, 'UTF-8');
if (strlen($output) > $limit) {
$output = substr($output, 0, $limit) . ' ... read more';
}
echo $output;
}
You can use it then like this:
<div id="post1">
<?php shorten('This is post one'); ?>
</div>

Related

I'm using trumbowyg as text editor for the textareas in my forum, but how do I echo it?

I didn't find any post related to my problem, so here I go :
I added trumbowyg (it's a WYSIWYG editor) to edit the content in my <textarea></textarea>, and it works just fine when I post it in my database.
Only problem is : how do I echo it ?
The parsing method of trumbowyg takes this form : you click on, let's say B in the toolbar on top of the textarea, and it will put your text in bold weight. But in the server, once posted, it takes actually this form : <strong>some text</strong>.
Obviously, when I echo the var stocking the data in this part of my sql request, it output it the same way : <strong>some text</strong> and not some text.
I don't know if it's actually so simple that I can't seem to find the solution, or if I'm trying something impossible... ?
Thanks by advance guys !
Well... Guess it was so obvious that I didn't find the answer in here. If it can help people who find themselves in the same situation as me : just wrap your var containing html with html_entity_decode($var)
That's it.
See below (textarea is showed if the user consulting the profile is the one wich it belongs to, else it just echo the descrption (called in an Action.php file, I didn't put the "requires" before the <!DOCTYPE html> declaration.
<!DOCTYPE html>
<html lang="en">
<?php include "includes/head.php"; ?>
<body>
<?php include ("includes/navbar.php") ?>
<div class="container">
<h2><?= $user_pseudo;?></h2>
<h5><?= $user_access_level;?></h5>
<?php
if($_SESSION['id'] == $user_id){
?>
<form method="POST">
<textarea id="parse" name="description"><?= $user_description; ?></textarea>
<button class="btn btn-primary" name="validate" type="submit">Mettre à jour</button>
</form>
<?php
} else {
?>
<br/><br/><br/>
<div class="container">
<?= html_entity_decode($user_description) ?>
</div>
</div>
<?php
}
?>
<script src="//ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>window.jQuery || document.write('<script src="js/vendor/jquery-3.3.1.min.js"><\/script>')</script>
<script src="trumbowyg/dist/trumbowyg.min.js"></script>
<script>
$('#parse').trumbowyg();
</script>
</body>
</html>

Hide Div From those who visit directly to the page but don't who refer from a exact domain using php

I want to hide a div from direct users but showing the same div to those who come from example.com
eg.
example123.com/article.php have below div
<div id="main">Title</div>
(when user click on a hyperlink on example.com
Artile
then show the above div
but when user come directly to example123.com/article.php then don't show the div.
how will I do that using php?
Hi you can use the following code like this.
<?php if (isset($_SERVER['HTTP_REFERER'])){ ?>
<div style="width:200px;height:200px;border:1px solid black">
<?php } ?>
You need to make use of $_SERVER['HTTP_REFERER']
I don't totally follow your question but this code should be enough for you to adapt to your needs:
if(strstr($_SERVER['HTTP_REFERER'],'example.com')) {
echo '<div id="main">Title</div>';
}
So, if the referrer URL contains example.com then echo your div.
If the referral URL didn't contain example.com or was empty (i.e. they arrived directly at your site) then the div won't show.
You can achieve this by passing an argument from the URL. The value of the argument will be null if they access the page directly and only have a value if they use the specific URL. Then your PHP can just check the argument and handle it accordingly.
Example as follows.
index.php
<!DOCTYPE html>
<html>
<head>
<title>Nothing</title>
</head>
<body>
<h1>Nothing 01</h1>
Regular URL
<br />
Argument URL
</body>
</html>
Then you can handle the Arguments in your PHP page containing the div
pagewithdiv.php
<!DOCTYPE html>
<html>
<head>
<title>Nothing</title>
</head>
<body>
<h1>Nothing 02</h1>
<div id="conditional">
<h2>Conditional Div</h2>
</div>
<?php
if (
// check if argument exists
isset($_GET["Condition"])
&&
// check if argument value is true
trim($_GET["Condition"] == true)
) {
echo '<script>';
echo 'document.getElementById("conditional").style.display = "block"';
echo '</script>';
} else {
echo '<script>';
echo 'document.getElementById("conditional").style.display = "none"';
echo '</script>';
}
?>
</body>
</html>
Keep in mind though that this is only hiding the div, it still exists on the page. If you want it to be completely gone then instead of using javascript to change the visibility you can echo the code that makes up the div if the requirements are met.
<!DOCTYPE html>
<html>
<head>
<title>Nothing</title>
</head>
<body>
<h1>Nothing 02</h1>
<?php
if (
// check if argument exists
isset($_GET["Condition"])
&&
// check if argument value is true
trim($_GET["Condition"] == true)
) {
echo '<div id="conditional">';
echo ' <h2>Conditional Div</h2>';
echo '</div>';
}
?>
</body>
</html>

echo text alongside a generated value PHP

I'm using this line of php in my main page
echo generateRadioButtons("fbresponse.php", "moRating1", 6);
Which when posting the following on the response file
echo $_POST['moRating1']
It works fine and displays the correct result, but! my question is how would i add text to that so..
Blah blah blah, you rated x question: 'moRating1'
I've tried doing
<html>
<head>
<title>Questions</title>
</head>
<body>
<h1>Survey responses</h1>
<p>How well did you rate it : <?php print $moRating1 ?></p>
</body>
</html>
inside the response file but that just doesnt load anything..
Any help please!
It's probably because this function uses eval() to execute its content (I guess it from lack of PHP tags in your first example).
If it's true, then you should be able to close PHP tag, print HTML and open it again.
?>
<html>
<head>
<title>Questions</title>
</head>
<body>
<h1>Survey responses</h1>
<p>How well did you rate it : <?php print $_POST['moRating1'] ?></p>
</body>
</html>
try doing:
$mRating1 = $_POST['moRating1'];
...
?>
...
<p>How well did you rate it: <?php echo $mRating1?></p>

How to target a php created div with jquery?

I'm trying to grab the first <div> of a set created by a php command, the problem is I can't seem to get the function to work or run after the divs have been created.
The php creates 5 <div>s when the page loads and i want to hide the first one.
Here is an example I made to help you:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>StackOverflow :: Help</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script>
$(document).ready(function() {
$('div.mydiv:first').hide();
});
</script>
</head>
<body>
<?php
echo "<div class='mydiv'>DIV 1</div>";
echo "<div class='mydiv'>DIV 2</div>";
echo "<div class='mydiv'>DIV 3</div>";
echo "<div class='mydiv'>DIV 4</div>";
echo "<div class='mydiv'>DIV 5</div>";
?>
</body>
</html>
You can try this example and see that the first div is actually hidding when the page loads. Hope this helps you.
You can try the following, give each div a class, like this:
<div class="mydiv"></div>
After that, with jQuery you can hide the first div like this:
$(document).ready(function() {
$('div.mydiv:first').hide();
});
If you have a unique id, you can get to the element like so:
<div id="div1"></div> <!--get this div -->
<div id="div2"></div>
$('#div1').hide();
Otherwise, if you have a class name associated with the group of <div>s, you can access the first one like so:
<div class="myClass"></div> <!--get this div -->
<div class="myClass"></div>
$('.myClass')[0].hide();
If you don't have any class or id for the <div>, you can access it like this: var myDiv = $('div')[i];, where i is the zero-based index number for the <div> that you want if you were to place all the <div>s in your webpage in order in an array. For example, if the <div> you want to access is the 2nd div that occurs on the page, you would access it using var myDiv = $('div')[1];
<div id="randomDiv"></div>
<div></div> <!--get this div -->
<div></div>
$('div')[1].hide();
As you might have noticed, the way you select elements by id, class, and tag in JQuery is identical to the way you would reference those items with CSS.

php template for different pages with different css and mysql

Hi I'm trying to figure out how to do a PHP template system with a class, i dont like header.php footer.php or smarty or whatever blabla, just want the template.html, the class.php and page1.php, page2.php etc... with my own php code, and I've found a lot of website of people teaching how to do this but i still have lots of questions.
1) i want to add EXTRA css to some pages
2) SOME pages has php code like mysql queries and stuff like that
3) the CONTENT which would be a variable where ever i want in the template is not only words, instead is a large amount of divs and stuff, also in some pages the CONTENT variable has queries inside, like fillin a (e.g)dropdown menu.
Hope somebody can guide me in this, i actually have my tempalte for explame, (the tags are just random)
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta content="text/html; charset=utf-8" http-equiv="Content-Type" />
<meta http-equiv="X-UA-Compatible" content="IE=8" />
<title>CompanyName | ##TITLE##</title>
<link href="layout.css" rel="stylesheet" type="text/css" />
<link href="styles.css" rel="stylesheet" type="text/css" />
##EXTRA_CSS##
<link rel="shortcut icon" href="/favicon.ico" />
<!--[if IE 6]>
<script src="DD_belatedPNG_0.0.8a-min.js"></script>
<script>
DD_belatedPNG.fix('img, div');
</script>
<![endif]-->
##EXTA_JS##
</head>
<body>
<div id="main">
<div id="container_black">
<div id="container_white">
<div id="container_header">
<div id="logo_top"></div>
<div id="lineas_verticales_top">
<div class="volver_portada">Volver a portada</div>
<div class="english_spanish"><u>Español</u> | English</div>
</div>
<div id="nav_bar_black"><div id="nav_bar_red"><div id="nav_bar_yel">
<ul class="menuholder">
<li class="menu_principal">Principal</li>
<li class="menu_empresa">Empresa</li>
<li class="menu_productos">Productos</li>
<li class="menu_clientes">Clientes</li>
<li class="menu_recetas">Recetas</li>
<li class="menu_contacto">Contacto</li>
</ul>
</div></div></div>
<div id="topbg_degr"></div>
</div>
<div id="container_left">
<div id="conmargen_left_top"></div>
<div id="container_conmargen_left_middle">
##CONTENT##
</div>
<div id="conmargen_left_bottom"></div>
<!--[IF INDEX]
<div id="fono"></div>
<div id="dir"></div>
-->
</div>
<!--[IF INDEX]
<div id="nav"></div>
-->
<div id="container_right">
<div id="conmargen_right_top"></div>
<div id="container_conmargen_right_middle">
<!--[IF PAGE OR PAGE OR PAGE]
[ELSE IF]
[ELSE IF]
-->
</div>
<div id="conmargen_right_bottom"></div>
</div>
<!--[IF INDEX]
<div id="frame_facebook">
<span>CompanyName</span> en Facebook
<div class="breakL"></div>
<fb:like href="#" layout="button_count" show_faces="true" width="100" font="tahoma"></fb:like>
</div>
-->
<br/>
</div> <!-- cierre del container white -->
</div> <!-- cierre del container black -->
<div id="footer">
<div class="footer_comment">
CompanyName Todos los derechos reservados 2011
</div>
</div>
</div> <!-- cierre del main -->
<br/>
</body>
</html>
for instance contact.php, the content would be a form, and on the top of the page i have this huge php code, where i validate and all.
I'd really appreciate if somebody would put me in the right path to do this. thank you in advance.
There are probably a hundred different ways you could approach this, each with their own advantages and disadvantages - using databases and/or ajax calls and/or headers and footers as you already said. You really have to work out which way works best for your particular project or style of coding, or both.
However - if you really just want 'template.html', but have some pages with PHP, javascript, MySQL or whatever else in them - then I would suggest.
Create template.html with placeholders such as {PAGE_TITLE}, {MAIN_CONTENT} or whatever you need.
Create page1.php/page2.php etc and do any server side work, generate variables to match your placeholders. It might be handy to store them as an array, ie:
PAGE_VARS array(
['TITLE'] => My Page
['CONTENT'] => This is my page content
)
At the end of your 'page' script, load the entire contents of template.html into a string
$template = file_get_contents('template.html')
Then, build up your template with the replaced variables using either a basic loop:
foreach ($PAGE_VARS as $KEY=>$VALUE) {
$template = str_replace("{".$KEY."}",$VALUE,$template)
}
(Feel free to get clever and probably more efficient with some regular expressions above, this is just a quick example.)
Output your template.
echo $template;
You can create a quick class (class.php) like this that will be your 'template engine' :
class Template {
var $contents;
function load($file) {
if ($fp = fopen($file, "r")) {
$this->contents = fread($fp, filesize($file));
fclose($fp);
}
}
function replace($str,$var) {
$this->contents = str_replace("<".$str.">",$var,$this->contents);
}
function show() {
$search = array(
'/\t/', //Remove Tabs
'/<!--[^\[-]+?-->/', //Remove Comments
'/\n\n/' //Remove empty lines
);
$replace = array(
'',
'',
''
);
$this->contents = preg_replace($search, $replace, $this->contents);
echo $this->contents;
}
}
In your template.html file, add special tags where you want to put your content, like this :
<html><head></head>
<body>
<div id="id1"><page_title></div>
</body>
</html>
...
Then create a function to write inside the tags (one per zone) :
function writetitle($s) {
$GLOBALS['writes']++;
$GLOBALS['page_title'] .= $s;
return;
}
finally, in your page.php, call the class, write your content, and generate the page :
require_once('class.php');
//Load Class
$template = new Template;
$template->load("template.html");
//Some query :
$query = mysql_query('SELECT...');
$res = mysql_num_rows($query);
//write your content :
writetitle('my title, '.$res.'');
//Generate the page :
$template->show();
Doing this you can create as many zones as you want. writetitle act like echo, so you can make queries and everything you want.
I hope it helps.
Insetad of having PHP parsing your template files I would suggest writing the templates using PHP and not your own pseudo code.
It's perfectly valid to write
...
<body>
<?php if($fooBar == "hahahaha"):?>
The cool foobar link
<?php endif;?>
</body>
...
I would then create a layout file with all common html etc. Then using small template snippets to be inserted into the layout where the main content goes.
By having actual PHP code in your templates the PHP enginge can handle them and you don't have to write your own logic to handle loops, if statements etc.
Take a look at Zend Framework and you'll get a good idea of how you can write your template engine.

Categories