I have a simple content rotator that displays text like so:
<h4><span>Featured Article</span></h4>
<h2><span>Lorem ipsum dolor sit amet,</span> <span>consectetur adipisicing elit</span></h2>
<span class="author">by Cameron Drysdale</span>
As you can see the h2 has it's text split up into <span> tags. This is so I can achieve the following effect as seen here on the pink box: http://www.paperviewmagazine.com/
The problem is how to do this automatically as the header will be generated from a database and will not have the span tags by default. Any ideas on how I could use PHP to add in some tags to wrap certain parts of a title?
EDIT: I'm using WordPress and so the title would be shown like <?php the_title(); ?> and I'd probably want to split the text after x number of characters
EDIT2: I should note that the idea is to split the content using span tags so this could also be a possibility: <span>this is</span> <span>some text</span> <span>I'm sharing</span>
What is the criteria you use for splitting.
Assuming it's a comma (you could use number of words/letters etc), just split the string using
<? $arr= explode(",",$your_db_field);?>
<span><?=$arr[0]?></span><span><?=$arr[1]?></span>
Or if you haven't already designed the db, simply have two fields - title_line_1 and title_line_2. No need to split.
If your text has <br/> tags or \n you can split it in array and then iterate over it.
$lines = split('<br/>',$text);
foreach($lines as $line){
echo "<span>".$line."</span>";
}
of course you can also use the comma to split the text.
to split the text by char length btw. you can use this.
$lenght = 100;
$start = 0;
$lines = array();
while(strlen($text) < $start)) {
$lines[] = substr($text, $start, $start+$length);
$start += $length;
}
A few questions: Why is your content broken into two sections when your example shows that they are the same font? is there always going to be a comma followed by a line break?
Reason I ask is because you could simply insert your title into an array and explode() on the comma.
EDIT: I'm using WordPress and so the
title would be shown like and I'd probably want
to split the text after x number of
characters
Okay that makes more sense. As far as I'm aware, there's no need for you to use multiple tags:
<?php
$chars_per_line = 15;
$title = "This is my title and I hope you like my article";
$title_length = strlen($title);
$lines = ceil($title_length / $chars_per_line);
for ($i=0; $i<$lines; $i++) {
$pos_start = $i * 15;
$pos_end = $pos_start + ($chars_per_line - 1);
echo substr($title, $pos_start, $pos_end) . '<br />';
}
?>
You do not need a span to achive the wanted result. You could just encapsulate you h2 in a div with a fixed width and the content will automatically flow on two line if it's to long.
Just make sure if you use this technique to you non-breaking space ( ) as spaces between the last words to avoid orphans.
I you really want to break it on specific chars, I would then go with Mr. Zen's answer
Edit:
Here is a link to a valid demo http://jsfiddle.net/38srk/3/
Edit (again):
I still think that a full html/css solution is still the best, but if you really want to do it in PHP here is a beginning for your solution :
$str = 'Lorem ipsum dolor sit amet, consectetur adipisicing elit';
$words = explode(' ', $str);
$nbWords = count($words);
$nbWordsPerLine = 4;
$output = '<span>';
for($i = 0; $i < $nbWords; $i++) {
if($i % $nbWordsPerLine == 0
&& $i > 0
) {
$output .= '</span><span>';
}
$output .= $words[$i];
if ($i + 1 < $nbWords){
$output .= ' ';
}
}
$output .= '</span>';
echo $output;
This will give you something like that :
<span>Lorem ipsum dolor sit </span><span>amet, consectetur adipisicing elit </span>
Related
I have a string with HTML tags, $paragraph:
$paragraph = '
<p class="instruction">
<sup id="num1" class="s">80</sup>
Hello there and welcome to Stackoverflow! You are welcome indeed.
</p>
';
$replaceIndex = array(0, 4);
$word = 'dingo';
I'd like to replace the words at indices defined by $replaceIndex (0 and 4) of $paragraph. By this, I mean I want to replace the words "80" and "welcome" (only the first instance) with $word. The paragraph itself may be formatted with different HTML tags in different places.
Is there a way to locate and replace certain words of the string while virtually ignoring (but not stripping) HTML tags?
Thanks!
Edit: Words are separated by (multiple) tags and (multiple) whitespace characters, while not including anything within the tags.
Thanks for all the tips. I figured it out! Since I'm new to PHP, I'd appreciate it if any PHP veterans have any tips on simplifying the code. Thanks!
$paragraph = '
<p class="instruction">
<sup id="num1" class="s">80</sup>
Hello there and welcome to Stackoverflow! You are welcome indeed.
</p>
';
// Split up $paragraph into an array of tags and words
$paragraphArray = preg_split('/(<.*?>)|\s/', $paragraph, -1, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE);
$wordIndicies = array(0, 4);
$replaceWith = 'REPLACED';
foreach ($wordIndicies as $wordIndex) {
for ($i = 0; $i <= $wordIndex; $i++) {
// if this element starts with '<', element is a tag.
if ($paragraphArray[$i]{0} == '<') {
// push wordIndex forward to compensate for found tag element
$wordIndex++;
}
// when we reach the word we want, replace it!
elseif ($i == $wordIndex) {
$paragraphArray[$i] = $replaceWith;
}
}
}
// Put the string back together
$newParagraph = implode(' ', $paragraphArray);
// Test output!
echo(htmlspecialchars($newParagraph));
*Only caveat is that this may potentially produce unwanted spaces in $newParagraph, but I'll see if that actually causes any issues when I implement the code.
$text = preg_replace('/\b80\b|\bwelcome\b/', $word, $paragraph);
Hope this will help you :)
SimpleXML could come in handy as well:
$paragraph = '
<p class="instruction">
<sup id="num1" class="s">80</sup>
Hello there and welcome to Stackoverflow! You are welcome indeed.
</p>
';
$xml = simplexml_load_string($paragraph);
$xml->sup = $word;
This might not even be possible but I have quite a limited knowledge of PHP so I can't figure out if it is or not.
Basically I have a string $myText and this string outputs HTML in the following format:
<p>This is the main bit of text</p>
<small> This is some additional text</small>
My aim is to limit the number of characters displayed specifically within the <p> tag, for example 10 characters.
I have been playing around with PHP substr but I can only get this to work on all of the text, not just the text in the <p> tag.
Do you know if this is possible and if it is, do you know how to do it? Any pointers at all would be appreciated.
Thank you
The simplest solution is:
<?php
$text = '
<p>This is the main bit of text</p>
<small> This is some additional text</small>';
$pos = strpos($text,'<p>');
$pos2 = strpos($text,'</p>');
$text = '<p>' . substr($text,$pos+strlen('<p>'),10).substr($text,$pos2);
echo $text;
but it will work just for first pair of <p> ... </p>
If you need more, you can use regular expressions:
<?php
$text = '
<p>This is the main bit of text</p>
<small> This is some additional text</small>
<p>
werwerwrewre
</p>';
preg_match_all('#<p>(.*)</p>#isU', $text, $matches);
foreach ($matches[1] as $match) {
$text = str_replace('<p>'.$match.'</p>', '<p>'.substr($match,0,10).'</p>', $text);
}
echo $text;
or even
<?php
$text = '
<p>This is the main bit of text</p>
<small> This is some additional text</small>
<p>
werwerwrewre
</p>';
$text = preg_replace_callback('#<p>(.*)</p>#isU', function($matches) {
$matches[1] = '<p>'.substr($matches[1],0,10).'</p>';
return $matches[1];
}, $text);
echo $text;
However in those all 3 cases, all white characters are assumed as part of the string, so if the content of <p>...</p> starts with 3 spaces and you want to display only 3 characters, you simple display only 3 spaces, nothing more. Of course it can be quite easily modified, but I mentioned it to notice that fact.
And one more thing, quite possible you will need to use multibyte version of functions to get the result, so for example instead of strpos() you should use mb_strpos() and set earlier utf-8 encoding using mb_internal_encoding('UTF-8'); to make it working
You can achieve it by a quite simple way:
<?php
$max_length = 5;
$input = "<b>example: </b><div align=left>this is a test</div><div>another very very long item</div>";
$elements_count = preg_match_all("|(<[^>]+>)(.*)(</[^>]+>)|U",
$input,
$out, PREG_PATTERN_ORDER);
for($i=0; $i<$elements_count; $i++){
echo $out[1][$i].substr($out[2][$i], 0, $max_length).$out[3][$i]."\n";
}
these will work for any tag and any class or attribute within it.
ex. input:
<b>example: </b><div align=left>this is a test</div><div>another very very long item</div>
output:
<b>examp</b>
<div align=left>this </div>
<div>anoth</div>
I'm cleaning some html files by php script and I want to remove all the \n thingies that are not between a <tag></tag>.
<p>some text</p>
<- here are the bunch of \n I want to remove
<p>some other random
text with \n at fixed width
and that's great</p>
Any ideas ?
Many thanks.
Something like this will suffice ?
<?php
$html=<<<SOMECONT
<p>some text</p>
<p>some other random
text with \n at fixed width
and thats great</p>
SOMECONT;
$narr=array_filter(explode(PHP_EOL,$html),'strlen');
echo implode('',$narr);
OUTPUT :
<p>some text</p><p>some other randomtext with
at fixed widthand thats great</p>
EDIT : ALTERNATIVE
Might be more "dirty" but works. Afterall, removing all \n between htmltags can sometimes be as simple as removing empty lines from an exploded string of the original file.
$split = explode(PHP_EOL,$data);
$data= "";
for($i = 0; $i < count($split); $i++){
$line = $split[$i];
else if(strlen($line) > 0) $data .= $split[$i]."\n"; // filter
}
I'm familiar with PHP truncating text based on the maximum number of characters reached, however I am wanting to tweak this from characters to limit text to 10 lines before truncating it.
How could I go about in achieving this?
Here is what I'm using at the moment to limit the number of characters:
<?php $str = $profile['bio'];
$max = 510;
if(strlen($str) > $max) {
$str = substr($str, 0, $max) . '...'; } ?>
<?php echo $str ?>
Use explode() to turn the text into an array of lines, array_slice() to limit the amount of lines, and then implode() to put it all back together again:
<?php
$text = "long\nline\ntext\nhere";
$lines = explode("\n", $text);
$lines = array_slice($lines, 0, 10); //10 is how many lines you want to keep
$text = implode("\n", $lines);
?>
I think your best bet is to use pure css to limit the height of your text/container.
What is a "line" of text?
Pure text written in a form field?
Text from editor perhaps full of html tags inside?
Utf8 text with foreign characters?
I fail to see a common pattern to the phrase "line of text" so as to use whatever method to limit its length (thus its height).
If you still want to limit it with php, then i suggest using length limiters. There are countless posts here and on the web in general. But you should be careful of encoded data (non latin ones)
e.g.
<?php
$subject = data();
$p = "![\r\n]+!";
$subject = preg_split($p, $subject, 11);
$subject = array_slice($subject, 0, 10);
echo join("\r\n", $subject);
function data() {
return <<< eot
Mary had a little lamb,
whose fleece was white as snow.
And everywhere that Mary went,
the lamb was sure to go.
It followed her to school one day
which was against the rule.
It made the children laugh and play,
to see a lamb at school.
And so the teacher turned it out,
but still it lingered near,
And waited patiently about,
till Mary did appear.
"Why does the lamb love Mary so?"
the eager children cry.
"Why, Mary loves the lamb, you know."
the teacher did reply.
eot;
}
prints
Mary had a little lamb,
whose fleece was white as snow.
And everywhere that Mary went,
the lamb was sure to go.
It followed her to school one day
which was against the rule.
It made the children laugh and play,
to see a lamb at school.
And so the teacher turned it out,
but still it lingered near,
You can use this function:
<?php
// Original PHP code by Chirp Internet: www.chirp.com.au
// Please acknowledge use of this code by including this header.
function truncateLongText ($string, $limit, $break=".", $pad="...") {
// return with no change if string is shorter than $limit
$string = strip_tags($string, '<b><i><u><a><s><br><strong><em>');
if(strlen($string) <= $limit)
return $string;
// is $break present between $limit and the end of the string?
if ( false !== ($breakpoint = strpos($string, $break, $limit)) ) {
if($breakpoint < strlen($string) - 1) {
$string = substr($string, 0, $breakpoint) . $pad;
}
}
return $string;
}
Example usage:
$text = "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book.";
echo truncateLongText($text, 10);
// Lorem Ipsum is simply dummy text of the printing and typesetting industry...
I want to display the first 110 characters of a database entry. Pretty easy so far:
<?php echo substr($row_get_Business['business_description'],0,110) . "..."; ?>
But the above entry has html code in it that's been entered by the client. So it displays:
<p class="Body1"><strong><span style="text-decoration: underline;">Ref no:</span></strong> 30001<strong></stro...
Obviously no good.
I just want to strip out all html code, so I need to remove everything between < and > from the db entry THEN display the first 100 chars.
Any ideas anyone?
use strip_tags
$text = '<p>Test paragraph.</p><!-- Comment --> Other text';
echo strip_tags($text); //output Test paragraph. Other text
<?php echo substr(strip_tags($row_get_Business['business_description']),0,110) . "..."; ?>
Use PHP's strip_tags() function.
For example:
$businessDesc = strip_tags($row_get_Business['business_description']);
$businessDesc = substr($businessDesc, 0, 110);
print($businessDesc);
Remove all HTML tags from PHP string with content!
Let say you have string contains anchor tag and you want to remove this tag with content then this method will helpful.
$srting = '<a title="" href="/index.html"><b>Some Text</b></a>
Lorem Ipsum is simply dummy text of the printing and typesetting industry.';
echo strip_tags_content($srting);
function strip_tags_content($text) {
return preg_replace('#<(\w+)\b.*?>.*?</\1>#si', '', $text);
}
Output:
Lorem Ipsum is simply dummy text of the printing and typesetting industry.
use this regex: /<[^<]+?>/g
$val = preg_replace('/<[^<]+?>/g', ' ', $row_get_Business['business_description']);
$businessDesc = substr(val,0,110);
from your example should stay: Ref no: 30001
For my this is best solution.
function strip_tags_content($string) {
// ----- remove HTML TAGs -----
$string = preg_replace ('/<[^>]*>/', ' ', $string);
// ----- remove control characters -----
$string = str_replace("\r", '', $string);
$string = str_replace("\n", ' ', $string);
$string = str_replace("\t", ' ', $string);
// ----- remove multiple spaces -----
$string = trim(preg_replace('/ {2,}/', ' ', $string));
return $string;
}
Strip the string from HTML tags:
<?php
echo strip_tags("Hello <b>world!</b>");
?>
Strip the string from HTML tags, but allow tags to be used:
<?php
echo strip_tags("Hello <b><i>world!</i></b>","<i>");
?>
In laravel you can use following syntax
#php
$description='<p>Rolling coverage</p><ul><li>Brexit deal: May admits she would have <br></li></ul></p>'
#endphp
{{ strip_tags($description)}}
<?php $data = "<div><p>Welcome to my PHP class, we are glad you are here</p></div>"; echo strip_tags($data); ?>
Or if you have a content coming from the database;
<?php $data = strip_tags($get_row['description']); ?>
<?=substr($data, 0, 100) ?><?php if(strlen($data) > 100) { ?>...<?php } ?>
$string = <p>Awesome</p><b> Website</b><i> by Narayan</i>. Thanks for visiting enter code here;
$tags = array("p", "i");
echo preg_replace('#<(' . implode( '|', $tags) . ')(?:[^>]+)?>.*?</\1>#s', '', $string);
Try this