PHP Split array at space before certain qty of characters - php

I have an application that can only deal with text up to 100 characters in length per line.
However I do not want to be splitting mid-word in a sentence as that doesn't look very nice. Therefore we would need to find the space before the 100th Character and then add it into the array.
I was thinking using strrpos would work - but am unsure how to do the continuing so it has everything in one array
$textToDraw = 'this is a message that is over 100 characters long just to see how well that the breaks work';
$characterLimit = substr($textToDraw, 0, 100);
$textBeforeLimit = strrpos($characterLimit, ' ', 0);
Thanks
UPDATE. This is the current code I have to split the text into an array and then draw each line. However I need it to cut on the space before 100 characters - and not on a hardcoded 100 character limit.
for ($i = 0; $i < count($textToDraw); $i++) {
$splitPoint = 100;
if ( strlen($textToDraw[$i]) > $splitPoint ) {
$newTextLines = str_split($textToDraw[$i], $splitPoint);
array_splice($textToDraw, $i, 1, $newTextLines);
$i = $i + count($newTextLines) - 1;
}
}
foreach ($textToDraw as $actualTextToDraw) {
$page->drawText($actualTextToDraw, $this->x , $this->y , 'UTF-8');
}

You can use php function wordwrap as below. This Wraps a string to a given number of characters using a string break character.
<?php
$textToDraw = 'this is a message that is over 100 characters long just to see how well that the breaks work';
$newtext = wordwrap($textToDraw, 100, "<br />\n");
echo $newtext;
?>

Try wordwrap().
Wraps a string to a given number of characters using a string break character.
Example adapted from the documentation page:
<?php
$text = "The quick brown fox jumped over the lazy dog.";
$newtext = wordwrap($text, 20, "<br />\n");
echo $newtext;
// Outputs:
// The quick brown fox<br />
// jumped over the lazy<br />
// dog.
Update for new info in question:
Apply it to your needs:
$text = "Here's some example text that may or may not be really really long.";
$linedText = wordwrap($text, 20, "\n");
$lines = explode("\n", $linedText);
// Do whatever with $lines.

Related

Laravel get column length and turn into spaces [duplicate]

I want to like add space in sting with specified string length.
For example : Hello is my string & i set string length 30 so next string should be start after length 30 so it should be like Hello Next string.
I would like to add space..
I have used following code but it's not adding space it's take whole character but not added space.
<?php
$fistString ="Hello World";
$secondString ="Good";
echo str_pad($fistString, 45, ' ', STR_PAD_RIGHT).$secondString;
?>
it will be done by using this
$string_1 = "The quick brown fox jumped over the lazy dog.";
$string_2= " -space-or-anything- ";
$newtext = wordwrap($string_1, 20, " $string_2 <br>");
// it will add second string after every 20th character and also break the line
echo $newtext;
// result will be like
The quick brown fox -space-or-anything-
jumped over the lazy -space-or-anything-
dog.
as per my knowledge the answer is :-
<?php
$fistString ="Hello World";
$secondString ="Good";
$str=$fistString;
for ($i=0; $i < 30; $i++) {
$str.=' ';
}
$str.=$secondString;
echo $str;
?>
I did with my self with following way..
<?php
echo str_pad($string, 30, " &nbsp", STR_PAD_RIGHT).$secondString;
?>
Add space with specified string length in php
$temp ="optionA"
chunk_split($temp ,6,' ')
output : option A

How to break MySQL content(text+html content) into columns?

As a first, I'd like to mention that I understand how everyone feels towards asking questions without providing at least some trial or errors, yet this is purely a need to know knowledge, with that being said, I'll go ahead and ask.
I haven't been able to figure out how to break content let's say 600-1000 text words saved in a MySQL table into 3 sections, so that in between these sections it could include specific java or to make it easier to understand images.
Let's say we retrieve 800 word text from MySQL, the goal would be to do this.
Content
========= Section Break [image] ==========
Content
========= Section Break [image] ==========
I've got this so far, (went ahead and tried to save problems by not including anything), but it is breaking the text in the middle of the sentence, where I'd like to break at least at the last .(dot) on that line.
$text = stripslashes($article_content);
$first = strpos($text," ",strlen($text) / 2);
$col1 = substr($text, 0, $first);
$col2 = substr($text, $first);
echo $col1;
echo "this is the line break";
echo $col2;
and this one it does not print the <br/> ($separator).
$separator = "<br/>";
$text = stripslashes($article_content);
$first = ceil(strlen($text) / 3);
$string = substr($text, 0, $first);
$string = $separator;
$string = substr($text,$first,$first);
$string = $separator;
$string = substr($text,($first*2), $first);
echo $string;
The first I cannot get it to break at the last .(dot) in that line.
It does not print the separator, no idea why either, but the text
prints just fine.
Use a dot before the equalssign after the first instantiation of the variable $string to add to it in your second example.
$separator = "<br/>";
$text = stripslashes($article_content);
$first = ceil(strlen($text) / 3);
$string = substr($text, 0, $first);
$string .= $separator;
$string .= substr($text,$first,$first);
$string .= $separator;
$string .= substr($text,($first*2), $first);
echo $string;

preg_replace_callback highlight pattern not match in result

I have this code:
$string = 'The quick brown fox jumped over the lazy dog and lived to tell about it to his crazy moped.';
$text = explode("#", str_replace(" ", " #", $string)); //ugly trick to preserve space when exploding, but it works (faster than preg_split)
foreach ($text as $value) {
echo preg_replace_callback("/(.*p.*e.*d.*|.*a.*y.*)/", function ($matches) {
return " <strong>".$matches[0]."</strong> ";
}, $value);
}
The point of it is to be able to enter a sequence of characters (in the code above it's a fixed pattern), and it finds and highlights those characters in the matched word. The code I have now highlights the entire word. I'm looking for the most efficient way of highlighting the characters.
The result of the current code:
The quick brown fox jumped over the lazy dog and lived to tell about it to his crazy moped.
What I would like to have:
The quick brown fox jumped over the lazy dog and lived to tell about it to his crazy moped.
Did I take the wrong approach? It would be awesome if someone could point me in the right way, I've been searching for hours and didn't find what I was looking for.
EDIT 2:
Divaka's been a great help. Almost there.. I apologize if I haven't been clear enough on what my goal is. I will try to explain further.
- Part A -
One of the things I will be using this code for is a phone book. A simple example:
When following characters are entered:
Jan
I need it to match following examples:
Jan Verhoeven
Arjan Peters
Raj Naren
Jered Von Tran
The problem is that I will be iterating over the entire phone book, person-record per person-record. Each person also has email-addresses, a postal address, maybe a website, a extra note, ect.. This means that the text I'm actually search can contain anything from letters, numbers, special characters(&#()%_- etc..), newlines, and most importantly spaces. So an entire record (csv) might contain the following info:
Name;Address;Email address;Website;Note
Jan Verhoeven;Veldstraat 2a, 3209 Herkstad;jan#werk.be;www.janophetwerk.be,jan#telemet.be;Jan die ik ontmoet heb op de bouwbeurs.\n Zelfstandige vertegenwoordiger van bouwmaterialen.
Raj Naren;Kerklaan 334, 5873 Biep;raj#werk.be;;Rechtstreekse contactpersoon bij Werk.be (#654 intern)
The \n is meant to be an actual newline. So if I search for #werk.be, I'd like to see both these records as a result.
- Part B -
Something else I want to use this for is searching song-texts. When I'm looking for a song and I can only remember it had to do something with ducks or docks and a circle, I would enter dckcircle and get the following result:
... and the ducks were all dancing in a great big circle, around the great big bonfire ...
To be able to fine-tune the searching I'd like to be able to limit the number of spaces (or any other character), because I would imagine it finding a simple pattern like eve in every song while I'm only looking for a song that has the exact word eve in it.
- Conclusion -
If I summarize this in pseudo-regex, for a search pattern abc with a max of 3 spaces in-between it would be something like this: (I might be totally off here)
(a)(any character, max 3 spaces)(b)(any character, max 3 spaces)(c)
Or more generic:
(a)({any character}{these characters with a limit of 3})(b)({any character}{these characters with a limit of 3})(c)
This can even be extended to this fairly easily I'm guessing:
(a)({any character}{these characters with a limit of 3}{not these characters})(b)({any character}{these characters with a limit of 3}{not these characters})(c)
(I know the ´{}´ brackets are not to be used that way in a regular expression, but I don't know how else to put it without using a character that has a meaning in regular expressions.)
If anyone wonders, I know the sql like statement would be able to do 80% (I'm guessing, might even be more) of what I'm trying to do, but I'm trying to avoid using a database to make this as portable as possible.
When the correct answer has been found, I'll clean this question (and the code) up and post the resulting php-class here (maybe I'll even put it up on github if that would be useful), so anyone looking for the same will have a fully working class to work with :).
I've came up with this. Tell me if it's what you want!
//$string = "The quick brown fox jumped over the lazy dog and lived to tell about it to his crazy moped.";
$string = "abcdefo";
//$pattern_array1 = array(a,y);
//$pattern_array2 = array(p,e,d);
$pattern_array1 = array(e,f);
$pattern_array2 = array(o);
$pattern_array2 = array(a,f);
$number_of_patterns = 2;
$regexp1 = generate_regexp($pattern_array1, 1);
$regexp2 = generate_regexp($pattern_array2, 2);
$string = preg_replace($regexp1["pattern"], $regexp1["replacement"], $string);
$string = preg_replace($regexp2["pattern"], $regexp2["replacement"], $string);
$string = transform_multimatched_chars($string);
// transforming other chars after transforming the multimatched ones
for($i = 1; $i <= $number_of_patterns; $i++) {
$string = str_replace("#{$i}", "<strong>", $string);
$string = str_replace("#/{$i}", "</strong>", $string);
}
echo $string;
function generate_regexp($pattern_array, $pattern_num) {
$regexp["pattern"] = "/";
$regexp["replacement"] = "";
$i = 0;
foreach($pattern_array as $key => $char) {
$regexp["pattern"] .= "({$char})";
$regexp["replacement"] .= "#{$pattern_num}\$". ($key + $i+1) . "#/{$pattern_num}";
if($key < count($pattern_array) - 1) {
$regexp["pattern"] .= "(?s)((?:(?!{$pattern_array[$key + 1]})(?!\s).)*)";
$regexp["replacement"] .= "\$".($key + $i+2) . "";
}
$i = $key + 1;
}
$regexp["pattern"] .= "/";
return $regexp;
}
function transform_multimatched_chars($string)
{
preg_match_all("/((#[0-9]){2,})(.*)((#\/[0-9]){2,})/", $string, $matches);
// change this for your purposes
$start_replacement = '<span style="color:red;">';
$end_replacement = '</span>';
foreach($matches[1] as $key => $match)
{
$string = str_replace($match, $start_replacement, $string);
$string = str_replace($matches[4][$key], $end_replacement, $string);
}
return $string;
}

how can I count number of occurance of a word in a string while ignoring cases

I am trying to count the number of occurance of a given word while ignoring cases.
I have tried
<?php
$string = 'Hello World! EARTh in earth and EARth';//string to look into.
if(stristr($string, 'eartH')) {
echo 'Found';// this just show eartH was found.
}
$timesfound = substr_count($string, stristr($string, 'eartH'));// this count how many times.
echo $timesfound; // this outputs 1 instead of 3.
Lowercase the string before searching:
$string = 'Hello World! EARTh in earth and EARth';
$search = 'EArtH';
var_dump(substr_count(strtolower($string), strtolower($search))); // outputs 3
try substr_count()
<?php
$text = 'This is a test';
echo strlen($text); // 14
echo substr_count($text, 'is'); // 2
?>

PHP Wordwrap on an angle, increasing indentation each break

is it possible with php's wordwrap to add increased indentation each line break to essentially create wordwrapping on an angle?
If I understand your question correcly, you would like to produce an output like:
xxxxxxx
xxxxxxxxx
xxxxxxxxxxx
xxxxxxxxxxxxx
xxxxxxxxxxxxxxx
Obviously, replacing x with your text.
wordwrap built-in function does not support this feature but you still can write your own, with a simple loop. Change the max length on each iteration, and break your initial string (depending on your needs, where you find a space or wherever you want).
<?php
$text = "The quick brown fox jumped over the lazy dog.";
echo $return = costomwrap($text , 10);
function costomwrap($text , $len)
{
$str = '';
for($i=0;$i<strlen($text);$i = $i+$len)
{
$str .= substr($text , $i , $len ).'<br />';
$len--;
}
return $str;
}
?>
live demo http://codepad.org/v3ysqV5A.
here, <br /> not come on your programme.

Categories