I want to display just two lines of the paragraph.
How do I do this ?
<p><?php if($display){ echo $crow->content;} ?></p>
Depending on the textual content you are referring to, you might be able to get away with this :
// `nl2br` is a function that converts new lines into the '<br/>' element.
$newContent = nl2br($crow->content);
// `explode` will then split the content at each appearance of '<br/>'.
$splitContent = explode("<br/>",$newContent);
// Here we simply extract the first and second items in our array.
$firstLine = $splitContent[0];
$secondLine = $splitContent[1];
NOTE - This will destroy all the line breaks you have in your text! You'll have to insert them again if you still want to preserve the text in its original formatting.
If you mean sentences you are able to do this by exploding the paragraph and selecting the first two parts of the array:
$array = explode('.', $paragraph);
$2lines = $array[0].$array[1];
Otherwise you will have to count the number of characters across two lines and use a substr() function. For example if the length of two lines is 100 characters you would do:
$2lines = substr($paragraph, 0, 200);
However due to the fact that not all font characters are the same width it may be difficult to do this accurately. I would suggest taking the widest character, such as a 'W' and echo as many of these in one line. Then count the maximum number of the largest character that can be displayed across two lines. From this you will have the optimum number. Although this will not give you a compact two lines, it will ensure that it can not go over two lines.
This is could, however, cause a word to be cut in two. To solve this we are able to use the explode function to find the last word in the extracted characters.
$array = explode(' ', $2lines);
We can then find the last word and remove the correct number of characters from the final output.
$numwords = count($array);
$lastword = $array[$numwords];
$numchars = strlen($lastword);
$2lines = substr($2lines, 0, (0-$numchars));
function getLines($text, $lines)
{
$text = explode("\n", $text, $lines + 1); //The last entrie will be all lines you dont want.
array_pop($text); //Remove the lines you didn't want.
return implode("<br>", $text); //Implode with "<br>" to a string. (This is for a HTML page, right?)
}
echo getLines($crow->content, 2); //The first two lines of $crow->content
Try this:
$lines = preg_split("/[\r\n]+/", $crow->content, 3);
echo $lines[0] . '<br />' . $lines[1];
and for variable number of lines, use:
$num_of_lines = 2;
$lines = preg_split("/[\r\n]+/", $crow->content, $num_of_lines+1);
array_pop($lines);
echo implode('<br />', $lines);
Cheers!
This is a more general answer - you can get any amount of lines using this:
function getLines($paragraph, $lines){
$lineArr = explode("\n",$paragraph);
$newParagraph = null;
if(count($lineArr) > 0){
for($i = 0; $i < $lines; $i++){
if(isset($lines[$i]))
$newParagraph .= $lines[$i];
else
break;
}
}
return $newParagraph;
}
you could use echo getLines($crow->content,2); to do what you want.
Related
My problem is it just replicates the number twice, though it does add the break when there is a number, but I'm trying to check if there is a number after the number, so it would say line 12 is.....
Thanks for any help
<?PHP
$lines = file_get_contents('http://www.webstitcher.com/test.txt');
$tag = str_split($lines); // puts all lines into a array
foreach ($tag as $num => $letta){
if (is_numeric($letta) == TRUE){
$num2 = $num++;
if (is_numeric($tag[$num2])){ // checks if next line is going to be another digit
$letta .= $tag[$num2];
unset($tag[$num2]); // removes line if it had another digit and adds to ouput
}
echo '<br />' . $letta;
}
else {
echo $letta;
}
}
?>
Try exploding the string using ' ' as the delimiter. This will allow you to keep the numbers whole and will ultimately help cut out a lot of the complexity.
$lines = file_get_contents('http://www.webstitcher.com/test.txt');
$tag = explode(' ', $lines); // puts all words into a array
foreach ($tag as $word){
if (is_numeric($word)) {
// if the word is numeric, simply skip to next line
// if you need to keep the number, add $word to the echo statement
echo '<br />';
}
else {
echo ' '.$word;
}
}
This way you don't have to keep track of the previous element in the array or check for the next element.
Alternatively, you could also use preg_replace which would remove the need for the loop entirely.
$lines = preg_replace('/[0-9]+/', '<br>', $words);
I have a php value coming back from my database as a string, like
"this, that, another, another"
And I'm trying to wrap a separate link around each of those strings, but I can't seem to get it to work. I've tried a for loop, but since it's just a string of information and not an array of information that doesn't really work. Is there a way to wrap a unique link around each value in my string?
The easiest way that I see to do this would be using PHP's explode() function. You'll find that it will become very useful as you start to use PHP more and more, so do check out its documentation page. It allows you to split a string up into an array given a certain separator. In your case, this would be ,. So to split the string:
$string = 'this, that, another, another 2';
$parts = explode(', ', $string);
Then use a foreach (again, check the documentation) to iterate through each of the parts and make them into a link:
foreach($parts as $part) {
echo '' . $part . "\n";
}
However, you can do this with a for loop. Strings can be accessed like arrays, so you can implement a parser pattern to parse the string, extract the parts, and create the links.
// Initialize some vars that we'll need
$str = "this, that, another, another";
$output = ""; // final output
$buffer = ""; // buffer to hold current part
// Iterate over each character
for($i = 0; $i < strlen($str); $i++) {
// If the character is our separator
if($str[$i] === ',') {
// We've reached the end of this part, so add it to our output
$output .= '' . trim($buffer) . "\n";
// clear it so we can start storing the next part
$buffer = "";
// and skip to the next character
continue;
}
// Otherwise, add the character to the buffer for the current part
$buffer .= $str[$i];
}
echo $output;
(Codepad Demo)
A better way is to do it like this
$string = "this, that, another, another";
$ex_string = explode(",",$string);
foreach($ex_string AS $item)
{
echo "<a href='#'>".$item."</a><br />";
}
First explode the string to get the individual words in an array. Then add the hyperlinks to the words and finally implode them.
$string = "this, that, another, another";
$words = explode(",", $string);
$words[0] = $words[0]
$words[1] = $words[1]
..
$string = implode(",", $words);
You can also use the for loop to assign hyperlinks that follow a pattern like this:
for ($i=0; $i<count($words); $i++) {
//assign URL for each word as its name or index
}
I have a very long text, and I need to cut the text after N chars, so that at the end I obtain a text, rendered on multiple rows, without any of the words being cut;
So, if a have a text with the lenght of a 1000 chars, which has been saved on 1 line, and I need to cut from 100 to 100 chars, at the end, I will get a text spread on 10 lines.
I tryed something, but I got stuck;
foreach does not work, the text is not seen a a array; also, i did not made sure to keep the words intact in my test;
Has anyone tryed this? Or is there any link with solution?
public static function cut_line_after_n_chars($str, $n = 70) {
$result = '';
$pos = 0;
foreach ($str as $c) {
$pos++;
if ($pos == $n) {
$result .= $c + '<br/>';
$pos = 0;
}
else
$result .= $c;
}
return $result;
}
It sounds like you need wordwrap.
http://php.net/manual/en/function.wordwrap.php
This allows you to break a string into an array of pieces without cutting off words. You can then format these pieces as you like.
EDIT
If you still need each of your lines to be 100 characters, you can use str_pad to add extra spaces onto each row.
Use explode() function to get array of words from your string.
$words = explode( ' ', $str );
$length = 0;
foreach( $words as $word ) {
// Your loop code goes here.
}
here's the line of code that I came up with:
function Count($text)
{
$WordCount = str_word_count($text);
$TextToArray = explode(" ", $text);
$TextToArray2 = explode(" ", $text);
for($i=0; $i<$WordCount; $i++)
{
$count = substr_count($TextToArray2[$i], $text);
}
echo "Number of {$TextToArray2[$i]} is {$count}";
}
So, what's gonna happen here is that, the user will be entering a text, sentence or paragraph. By using substr_count, I would like to know the number of occurrences of the word inside the array. Unfortunately, the output the is not what I really need. Any suggestions?
I assume that you want an array with the word frequencies.
First off, convert the string to lowercase and remove all punctuation from the text. This way you won't get entries for "But", "but", and "but," but rather just "but" with 3 or more uses.
Second, use str_word_count with a second argument of 2 as Mark Baker says to get a list of words in the text. This will probably be more efficient than my suggestion of preg_split.
Then walk the array and increment the value of the word by one.
foreach($words as $word)
$output[$word] = isset($output[$word]) ? $output[$word] + 1 : 1;
If I had understood your question correctly this should also solve your problem
function Count($text) {
$TextToArray = explode(" ", $text); // get all space separated words
foreach($TextToArray as $needle) {
$count = substr_count($text, $needle); // Get count of a word in the whole text
echo "$needle has occured $count times in the text";
}
}
$WordCounts = array_count_values(str_word_count(strtolower($text),2));
var_dump($WordCounts);
I'm looking for a way to make word-wrap in PHP a bit smarter. So it doesn't pre-break long words leaving any prior small words alone on one line.
Let's say I have this (the real text is always completely dynamic, this is just to show):
wordwrap('hello! heeeeeeeeeeeeeeereisaverylongword', 25, '<br />', true);
This outputs:
hello!
heeeeeeeeeeeeeeereisavery
longword
See, it leaves the small word alone on the first line.
How can I get it to ouput something more like this:
hello! heeeeeeeeeeee
eeereisaverylongword
So it utilizes any available space on each line. I have tried several custom functions, but none have been effective (or they had some drawbacks).
I've had a go at the custom function for this smart wordwrap:
function smart_wordwrap($string, $width = 75, $break = "\n") {
// split on problem words over the line length
$pattern = sprintf('/([^ ]{%d,})/', $width);
$output = '';
$words = preg_split($pattern, $string, -1, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE);
foreach ($words as $word) {
if (false !== strpos($word, ' ')) {
// normal behaviour, rebuild the string
$output .= $word;
} else {
// work out how many characters would be on the current line
$wrapped = explode($break, wordwrap($output, $width, $break));
$count = $width - (strlen(end($wrapped)) % $width);
// fill the current line and add a break
$output .= substr($word, 0, $count) . $break;
// wrap any remaining characters from the problem word
$output .= wordwrap(substr($word, $count), $width, $break, true);
}
}
// wrap the final output
return wordwrap($output, $width, $break);
}
$string = 'hello! too long here too long here too heeeeeeeeeeeeeereisaverylongword but these words are shorterrrrrrrrrrrrrrrrrrrr';
echo smart_wordwrap($string, 11) . "\n";
EDIT: Spotted a couple of caveats. One major caveat with this (and also with the native function) is the lack of multibyte support.
How about
$string = "hello! heeeeeeeeeeeeeeereisaverylongword";
$break = 25;
echo implode(PHP_EOL, str_split($string, $break));
Which outputs
hello! heeeeeeeeeeeeeeere
isaverylongword
str_split() converts the string to an array of $break size chunks.
implode() joins the array back together as a string using the glue which in this case is an end of line marker (PHP_EOL) although it could as easily be a '<br/>'
This is also a solution (for browsers etc.):
$string = 'hello! heeeeeeeeeeeeeeeeeeeeeereisaverylongword';
echo preg_replace('/([^\s]{20})(?=[^\s])/', '$1'.'<wbr>', $string);
It puts a <wbr> at words with 20 or more characters
<wbr> means "word break opportunity" so it only breaks if it has to (dictated by width of element/browser/viewer/other). It's invisible otherwise.
Good for fluid/responsive layout where there is no fixed width. And does not wrap odd like php's wordwrap
You can use CSS to accomplish this.
word-wrap: break-word;
That will break the word for you. Here is a link to see it in action:
http://www.css3.info/preview/word-wrap/
This should do the trick...
$word = "hello!" . wordwrap('heeeeeeeeeeeeeeereisaverylongword', 25, '<br />', true);
echo $word;