how to get first some line from a paragraph - php

I have a paragraph stored in database i want to get only first five line from . it how to do this ?
should i convert first array to srting ? if yes then how to do this ?
if its string than i can do this by
$str='mayank kumar swami mayank kumar swami';
$var= strlen($str);
for($i=0;$i<8;$i++){
echo $str[$i];
}
or how to get only 200 word from the database by sql ?
i know it can be done by css easily shows in Show first line of a paragraph nut i want to do this by php or sql query
what i doing
$article_result = mysql_query("SELECT * FROM article ORDER BY time DESC LIMIT 1",$connection);
if($article_result){
while($row = mysql_fetch_array($article_result))
{
echo "<div class=\"article_div\" >";
echo "<h4 id=\"article_heading\"><img src=\"images/new.png\" alt=\"havent got\" style=\"padding-right:7px;\">".$row['article_name']."</h4>";
echo"<h5 class=\"article_byline\">";
echo" by";
echo"{$row['authore']}</h5>";
echo" <div id=\"article_about\"><p>{$row['content']}</p></div>";
//here i want to get only 2000 word from database (content)
echo "</div>";
}
}

There are a number of solutions to this problem.
If you want to split it by number of words, something similar to what user247245 posted:
function get_x_words($string,$x=200) {
$parts = explode(' ',$string);
if (sizeof($parts)>$x) {
$parts = array_slice($parts,0,$x);
}
echo implode(' ',$parts);
}
My preferred method however is getting all the full words up until a certain point (e.g. 200 characters):
function chop_string($string,$x=200) {
$string = strip_tags(stripslashes($string)); // convert to plaintext
return substr($string, 0, strpos(wordwrap($string, $x), "\n"));
}
The above will chop the string at 200 characters, however will only chop it after the end of a word (so you won't get half a word returned at the end)

Are we talking words, lines or letters?
If words:
$a = explode(' ',$theText);
if (sizeof($a)>200) $a = array_slice($a,0,200);
echo implode(' ',$a);
regards,

You can use substring function in mysql
SELECT SUBSTRING('Quadratically',1,5);
returns
Quadr
I suggest you do with sql as it reduces the amount of data transfer between you db server and application server.
So, Now you modify to this
$article_result = mysql_query("SELECT article_name, authore, SUBSTRING(content,1,200) as content FROM article ORDER BY time DESC LIMIT 1",$connection);

Try This:
<?php
echo substr("mayank kumar swami mayank kumar swami", 0, 6);
?>
Result Output: mayank

<?php
$about_vendor ="Lorem ipsum dolor sit amet, consectetur adipisicing elit. Adipisci officia excepturi quisquam mollitia, obcaecati cupiditate, quaerat est quibusdam nostrum esse culpa voluptates eum, et architecto animi. Voluptates enim tenetur minus! Lorem ipsum dolor sit amet, consectetur adipisicing elit. Laboriosam magni exercitationem non at error possimus, voluptas aut, aperiam sint pariatur illo libero vel aspernatur tempora laborum. Harum nesciunt quos at. Lorem ipsum dolor sit amet, consectetur adipisicing elit. Vitae quidem saepe voluptates minus delectus, dolores, repellat maiores quae consectetur quasi qui voluptas eius odit autem optio cupiditate nesciunt iste ducimus!"
// Convert string to array
$convert_to_array = explode(' ',$about_vendor);
// Total length of array
$total_length_of_array = count($convert_to_array);
?>
<p class="tip_par" style="text-align:justify;">
<!-- specify how many words do you want to show, I like to show first 30 words -->
<?php for($i=0;$i<=30;$i++) {
echo $convert_to_array[$i].' ';
} ?>
<!-- If you have more than 30 word it will show on toggle click on below more link -->
<span style="color:#C1151B;"> <span data-toggle="collapse" data-target="#demo" style="cursor:pointer;"><?php if($total_length_of_array >30) {
echo "more";
} ?></span>
<div id="demo" class="collapse tip_par" style="padding-top: 0px;">
<?php for($i=31;$i<$total_length_of_array;$i++) {
echo $convert_to_array[$i].' ';
} ?>
</div>
</span> </p>

Related

How to make node <options> without closing tag </options> in XML? [duplicate]

I want to create a html block, like this:
<media>
<media-reference source='15.jpg' />
<media-caption>caption</media-caption>
<hasSyndicationRights>1</hasSyndicationRights>
<licenseId>1</licenseId>
<licensorName>name</licensorName>
</media>
But in my code <media-reference> closes like this </media-reference>.
How can I close just that tag?
This is my code:
$valFieldBody = '<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Odio labore aut hic soluta! Animi quaerat unde commodi minus dicta, a quidem. Soluta quaerat delectus, id, dolor ex placeat molestiae quae.</p><p><img height="500" src="15.jpg" width="500"/></p>';
$htmlEncoded = mb_convert_encoding($valFieldBody, 'HTML-ENTITIES', 'UTF-8');
$doc = new DOMDocument;
$opcionesLibXML = LIBXML_COMPACT | LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD;
libxml_use_internal_errors(true);
#$doc->loadHTML($htmlEncoded, $opcionesLibXML);
libxml_use_internal_errors(false);
$img_tag = $doc->getElementsByTagName('img');
foreach ($img_tag as $key => $img_items){
$img_src = $img_items->getAttribute('src');
$tag_media = $doc->createElement('media');
$tag_media_reference = $doc->createElement('media-reference');
$tag_media_reference->setAttribute('mime-type','image/jpg');
$tag_media_reference->setAttribute('source',$img_src);
$tag_media_caption = $doc->createElement('media-caption',$img_title);
$tag_hasSyndicationRights = $doc->createElement('hasSyndicationRights','1');
$tag_licenseId = $doc->createElement('licenseId','1');
$tag_licensorName = $doc->createElement('licensorName',$img_title);
$tag_media->appendChild($tag_media_reference);
$tag_media->appendChild($tag_media_caption);
$tag_media->appendChild($tag_hasSyndicationRights);
$tag_media->appendChild($tag_licenseId);
$tag_media->appendChild($tag_licensorName);
$img_items->parentNode->replaceChild($tag_media, $img_items);
}
$valFieldBody = $doc->saveHTML($doc->documentElement);
For now I'm using str_replace to change that:
$valFieldBody = str_replace("></media-reference>"," />", $valFieldBody);
The problem is that saveHTML() is creating the output using it's own rules (as far as I can tell) and doesn't always write things according to XHTML standards. If instead you write it out using saveXML() you should get a more standard output
$valFieldBody = $doc->saveXML($doc->documentElement);
which gives...
<p>
Lorem ipsum dolor sit amet, consectetur adipisicing elit. Odio labore
aut hic soluta! Animi quaerat unde commodi minus dicta, a quidem.
Soluta quaerat delectus, id, dolor ex placeat molestiae quae.
<p>
<media>
<media-reference mime-type="image/jpg"
source="15.jpg" />
<media-caption>abcd</media-caption>
<hasSyndicationRights>1</hasSyndicationRights>
<licenseId>1</licenseId>
<licensorName>abcd</licensorName>
</media>
</p>
</p>
(Note that saving as XML may actually cause other problems if your original source isn't XHTML)

How do I paginate json data in php

I have json data that looks like this
{
"project_no":1693,
"project_name":"Theresa Project",
"description":"Nonumy euismod ornatus usu te, quodsi viderer accommodare sea cu, ut alterum officiis nec. At deleniti eloquentiam vis. Explicari definitionem ei sea. No nec erat fugit voluptaria, in his elit discere fastidii. Aperiri virtute no eos. Te per habemus vulputate, partem iuvaret intellegebat eam in.",
"project_cost":10000.00,
}
{
"project_no":1664,
"project_name":"School Supplies for Children",
"description":"Nonumy euismod ornatus usu te, quodsi viderer accommodare sea cu, ut alterum officiis nec. At deleniti eloquentiam vis. Explicari definitionem ei sea. No nec erat fugit voluptaria, in his elit discere fastidii. Aperiri virtute no eos. Te per habemus vulputate, partem iuvaret intellegebat eam in. ",
"project_cost":8000.00,
},
I have over 60 records, With php I want to show 10 records on each page and dynamically populate the page numbers based on how many records I have.
Heres how I'm displaying the data.
$json = file_get_contents('http://linktojsondata.com');
$obj = json_decode($json, true);
<?php
$i = 0;
foreach ($obj as $project_name => $project_info) { ?>
<a href="single-project-detail.php/<?php echo $project_info['project_no'];?>">
<img class="img-thumbnail" alt="" src="<?php echo $project_info['featured_image_url']; ?>">
</a>
<a href="single-project-detail.php/<?php echo $project_info['project_no'];?>">
<?php echo $project_info['project_name']; ?>
</a>
<p>
<?php $string = strip_tags($project_info['description']);?>
</p>
<?php if (++$i == 10) break; } ?>
Here is a start, you will split the json array into blocks of 10 using array_chunk, and then loop through this using the page number $_GET['p'] - 1 so your page url may look like page.php?p=2 which will select the second set of data.
$pages = array_chunk(json_decode($json, true), 10, true);
foreach ($pages[$_GET['p'] - 1] as $project_name => $project_info) {
// your code
}

Add line breaks to mysql textarea

I create a simple backed area for my client to post new job openings and was wanting to give them the ability to format the text a little by adding line breaks in the job description text that will be visible on the front end.
The job openings are stored in a MySQL database.
Example of what I'm talking about:
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla quis quam sollicitudin, bibendum enim a, vulputate turpis.
Nullam urna purus, varius eget purus quis, facilisis lacinia nibh. Ut in blandit erat.
I've would like the breaks to happen when my client hits enter / return on the keyboard.
Any help on this matter would be appreciated.
------------UPDATE------------
okay so after much trial and error I got it somewhat working.
I added this line in my upload / action code.
$description = nl2br(htmlspecialchars($_POST['description']));
Full upload code is:
<?php
include($_SERVER['DOCUMENT_ROOT'] . "/connections/dbconnect.php");
$date = mysql_real_escape_string($_POST["date"]);
$title = mysql_real_escape_string($_POST["title"]);
$description = mysql_real_escape_string($_POST["description"]);
$description = nl2br(htmlspecialchars($_POST['description']));
// Insert record into database by executing the following query:
$sql="INSERT INTO hire (title, description, date) "."VALUES('$title','$description','$date')";
$retval = mysql_query($sql);
echo "The position was added to employment page.<br />
<a href='employment.php'>Post another position.</a><br />";
?>
Then on my form I added this to the textarea, but I get an error.
FYI that is line 80 the error is refering to.
Position Details:<br />
<textarea name="description" rows="8"><?php echo str_replace("<br />","",$description); ?></textarea>
</div>
Here is what the error looks like.
Here is my results page code:
<?php
$images = mysql_query("SELECT * FROM hire ORDER BY ID DESC LIMIT 10");
while ($image=mysql_fetch_array($images))
{
?>
<li data-id="id-<?=$image["id"] ?>">
<div class="box white-bg">
<h2 class="red3-tx"><?=$image["title"] ?> <span class="date-posted blue2-tx"><?=$image["date"] ?></span></h2>
<div class="dotline"></div>
<article class="blue3-tx"><?=$image["description"] ?><br />
<br />
For more information please call ###-###-####.</article>
</div>
</li>
<?php
}
?>
If I delete all that error copy and write out a real position with line breaks it works.
I have no idea how to fix the error though.
Again any help would be appreciated.
Thanks!
you can use str_replace
$statement = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla quis quam sollicitudin, bibendum enim a, vulputate turpis.
Nullam urna purus, varius eget purus quis, facilisis lacinia nibh. Ut in blandit erat."
$statement = str_replace(chr(13),"<br/>", $statement);
query example : INSERT INTO table (statement) VALUES ('$statement');
hope this can help you
EDIT :
if you want display the result at textarea from database u can using this code
$des = $row['description'] //my assumption that your feild name at table inside mySQL is description
Position Details:<br />
<textarea name="description" rows="8"><?php echo str_replace("<br />",chr(13),$des); ?></textarea>
</div>
hope this edit can help your second problem
I would start by answering a couple of questions first
Do I want my database to store html-formatted user input?
Is the data going to be editable afterwards?
Since you seem to want only nl2br, a simple approach would be to save the content as is in the database, then use nl2br() on the output side as Marcin Orlowski suggested.

PHP preg_match_all run php function on matched items

I'm not sure of the terminology so I apologize ahead of time.
I'm trying to create a PHP template engine that will query a string for <ZONE header> and </ZONE header> and it will pull everything in between and then run a php function to see if the header exists. If the header exists it will display what was in between, and if the header does not exists it will remove what was in between.
Here's an example:
$string = "
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p>
<ZONE header><img src="images/header.jpg" /></ZONE header>
<p>Nam sollicitudin mattis nisi, eu convallis mi tincidunt vitae.</p>
";
The function would ideally remove <ZONE header><img src="images/header.jpg" /></ZONE header> then it will run the php function I've created header() which checks to see if the "header" exists in the database, and if it does, it will display everything inside <ZONE header></ZONE header> and if it doesn't it will remove it from the string.
If "header" exists:
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p>
<img src="images/header.jpg" />
<p>Nam sollicitudin mattis nisi, eu convallis mi tincidunt vitae.</p>
If "header" does not exist:
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p>
<p>Nam sollicitudin mattis nisi, eu convallis mi tincidunt vitae.</p>
Here is what I was working with but got stuck:
preg_match_all("|\<ZONE_header>(.*)\<\/ZONE_header>|isU", $string, $zone, PREG_SET_ORDER);
if (isset($zone) && is_array($zone)) {
foreach ($zone as $key => $zoneArray) {
if ($key == 0) {
$html = $zoneArray[1];
if ($html != "") {
if (header() != "") {
$html = str_replace($zoneArray[0], NULL, $html);
}
}
}
}
}
echo $html;
Any ideas, thoughts, suggestions?
Thank you for any and all help!
Note that I replace your header() function with get_header().
$string = preg_replace_callback('/<ZONE header>(.+)<\/ZONE header>/', 'replace_header', $string);
function replace_header($matches) {
return get_header() ? $matches[1] : '';
}
See documentation for preg_replace_callback.
Like this ?
$string = '
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p>
<ZONE header><img src="images/header.jpg" /></ZONE header>
<p>Nam sollicitudin mattis nisi, eu convallis mi tincidunt vitae.</p>
';
$pattern="#<ZONE header[^>]*>(.+)</ZONE header>#iU";
preg_match_all($pattern, $string, $matches);
if (strlen($matches[0][0])==0){
$string=strip_tags($string,"<p>");
}
else{
$string=strip_tags($string,"<p><img>");
}
echo $string;

Use PHP's preg_replace() to return only the value inside the <h1>?

How would I use PHP's preg_replace() to return only the value inside the <h1> in the following string (it's HTML text loaded in a variable called $html):
<h1>I'm Header</h1>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Pellentesque tincidunt porttitor magna, quis molestie augue sagittis quis.</p>
<p>Pellentesque tincidunt porttitor magna, quis molestie augue sagittis quis. Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p>
I've tried this: preg_replace('#<h1>([.*])</h1>.*#', '$1', $html), but to no avail. Am I regex-ing this correctly? And is there a better PHP function that I should be using instead of preg_replace?
Here is how you do it using preg_replace:
$header = preg_replace('/<h1>(.*)<\/h1>.*/iU', '$1', $html);
You can also use preg_match:
$matches = array();
preg_match('/<h1>(.*)</h1>.*/iU', $html, $matches);
print_r($matches);
([.*]) means dot OR astersk
What you need is (.*?), which means any amount of any characters ungreedy
or
([^<]*) - which means any amount of any characters but not <

Categories