Cut string into pieces without breaking words. - php

I have a string:
$str = 'Hello World, Welcome World, Bye World';
I want to cut above string into pieces. Each piece should be of 10 characters. If a word is going to be cut, then move that word to next line.
For Example:
$output = array();
$output[0] = 'Hello ';
$output[1] = 'World, ';
$output[2] = 'Welcome ';
$output[3] = 'World, Bye';
$output[4] = 'World';
Is there a shortest way without so many if else and loops.
Thanks

Use wordwrap. By default it wraps whole words and does not cut them into pieces.
echo wordwrap('Hello World, Welcome World, Bye World', 10);
If you want an array, explode afterwards:
print_r(explode("\n", wordwrap('Hello World, Welcome World, Bye World', 10)));

string test = 'Hello World, Welcome World, Bye World';
string[] splited = test.Split(' ');
foreach (string str in s.Split(splited))
{
Console.WriteLine(str);
}
Note: Its written in C#, I hope it will give you an Idea.
Regards

Although not exactly the answer, some similar problem is like this:
You have a long string, you want to break that string into chunks. You prefer not to break words, but words can be broken if word is very long.
$string = "Hello I am a sentence but I have verylongwordthat I can split";
You will split the words in this sentence if word is very long, like this:
$pieces = explode(" ",$string);
$textArray=array();
foreach ($pieces as $p) {
$textArray= array_merge($textArray, str_split($p, 10));
}
$stringNew=implode(" ",$textArray);
output:
"Hello I am a sentence but I have verylongwo rdthat I can split"

Related

Replacing string except certain parts

I'm writing a PHP app, and I have an input string in the form
Hello world. Hello [fbes_keep]world[/fbes_keep].
And a new string in the form
Hallo welt. Hello.
What I want it for the input string to be replaced by the new string, except the parts in the [fbes_keep] tags, so the output is
Hallo welt. Hello [fbes_keep]world[/fbes_keep].
My current approach involves using the finediff library but overriding the delete opcodes to look for the fbes tags. I asked a question about this yesterday, but I feel I may have run into the XY problem. Is there a better way?
Edit: Gist containing current (non-functional) code and real-world test case.
Maybe this is not the most elegant way how do I did it, but I've tested it, and it do the job:
$expression = 'world';
$newExpression = 'welt';
$str = 'Hello world. Hello [fbes_keep]world[/fbes_keep]. Here are some other world, and [fbes_keep]other[/fbes_keep] word in fbes.';
$pattern = '/\[fbes_keep\].*?\[\/fbes_keep\]/i';
$fbKepps = [];
preg_match_all($pattern, $str, $fbKepps);
$others = preg_split($pattern, $str);
$result = '';
$i = 0;
foreach ($others as $other) {
$result .= preg_replace('/' . addslashes($expression) . '/', $newExpression, $other);
$i++;
if ($i < count($others)) {
$result .= $fbKepps[0][$i - 1];
}
}
echo $result;
OUTPUT
Hello welt. Hello [fbes_keep]world[/fbes_keep]. Here are some other welt, and [fbes_keep]other[/fbes_keep] word in fbes.
My ideia is to split the string by [fbes_keep]...[/fbes_keep], but before store them in an array. Then iterate through all the rest, change the world to welt then concat the next fbes_keep and so on...
It keeps everything wher [fbes_keep]anything[/fbes_keep] and there are multiple fbes_keep can be in string with other words too.

PHP script to remove everything before the first occurrence of a number

What I'm trying to remove all data in a string before a the first occurrence of a number like (1-9) maybe in a function?
example:
$value = removeEverythingBefore($value, '1-10');
SO if i have a test like "Hello I want to rule the world in 100 hours or so"
I want this to find the first occurrence of a number which is 1 and delete everything before it.
Leaving me with 100 hours or so.
If you want to call the function like you mentioned in your post you can do like the below:
<?php
function removeEverythingBefore($value, $pattern) {
preg_match($pattern, $value, $matches, PREG_OFFSET_CAPTURE);
$initialPosition = $matches[0][1];
return substr($value, $initialPosition);
}
$value = "Hello I want to rule the world in 100 hours or so";
$value = removeEverythingBefore($value, '/[0-9]/');
echo $value; // prints 100 hours or so
This way you can use the same function to match other patters aswell.
You can use preg_replace for this with the regex /([a-z\s]*)(?=\d)/i like this:
$string = "Hello I want to rule the world in 100 hours or so";
$newString = preg_replace("/([a-z\s]*)(?=\d)/i", "", $string);
echo $newString; // Outputs "100 hours or so"
You can see an it working with this eval.in. If you wanted it in a function you could use this:
function removeEverythingBeforeNumber($string)
{
return preg_replace("/([a-z\s]*)(?=\d)/i", "", $string);
}
$newString = removeEverythingBeforeNumber("Hello I want to rule the world in 100 hours or so");
you could use strpos to get the index of the first occurence and then substr to get the string beginning from that index. Would be faster/more hardware friendly then regex i believe.

Get all of the text from a string after the first one sentence

So Currently I am using this code to get the first sentence only out of a string
preg_match('/^([^.!?]*[\.!?]+){0,1}/', $text, $abstract);
Can you please help me on how to create another regular expression to get the remaining text or get the text after the first sentence only ?
Thanks
This should give you the general idea using explode():
<?php
$string = 'Sentence one. Sentence two. Sentence three. Sentence four.';
$sentences = explode(".", $string);
echo $sentences[0]; // echos 'Sentence one'
echo $sentences[1]; // echos ' Sentence two'
echo $sentences[2]; // echos ' Sentence three'
echo $sentences[3]; // echos ' Sentence four'
// The following demonstrates how to do what you're asking, but I'm not quite
// sure what your specific use case is so adapt as necessary.
echo $sentences[0]; // echos 'Sentence one'
// to echo the remaining sentences do this
// start at 1 not 0 to skip the first sentence
for ($i = 1; $i < count($sentences); $i++)
{
echo $sentences[$i];
}
Note that this will treat any '.' as the end of a sentence so it may not be suitable in all cases, for example if you have 'I.T.' mid-sentence. Therefore the regular expression may be a more appropriate solution if you need this level of accuracy. Just let me know if you have any questions. : )
This might help you if you know how many sentences are exactly there in that string.
$str = "First Sentence.";
$str .= "Second Sentence. Third Sentence";
$result = explode(".",$str)[1].". ".explode(".",$str)[2];
echo $result;
UPDATE
Final Answer >>
$str = "First Sentence.";
$str .= "Second Sentence. Third Sentence";
$extract = strpos($str, ".")+1;
$result = substr($str, $extract, strlen($str));
echo $result;

alter word keeping the punctuation mark in its own position

I want a program in php that takes the first letter of word to the last and add "ay" at end. example:
I love my family becomes Iay ovelay ymay amilyfay
I did this to get my result:
<?php
$var = "I love my family";
$words = explode(" ",$var);
$final = "";
foreach ($words as $word){
$n = "";
for($i=1;$i<strlen($word);$i++){
$n .= $word{$i};
}
$n .= $word{0}."ay";
$final .= $n." ";
}
echo $final;
?>
but this doesnt work when the input is: he says, "I love my family". this gives output as: ehay ays,say I"ay ovelay ymay amily"fay where I need the punctuation marks to be in their own position like this: ehay ayssay, "Iay ovelay ymay amilyfay"
Tried alot but found nothing that works
Looks like something along the lines of:
$str = 'he says, "I love my family"';
$str = preg_replace('/(\w{1})(\w*)/', "$2$1ay", $str);
echo $str; // ehay ayssay, "Iay ovelay ymay amilyfay"
Should get you at least most of the way there.

How can we split a sentence

I have written the PHP code for getting some part of a given dynamic sentence, e.g. "this is a test sentence":
substr($sentence,0,12);
I get the output:
this is a te
But i need it stop as a full word instead of splitting a word:
this is a
How can I do that, remembering that $sentence isn't a fixed string (it could be anything)?
use wordwrap
If you're using PHP4, you can simply use split:
$resultArray = split($sentence, " ");
Every element of the array will be one word. Be careful with punctuation though.
explode would be the recommended method in PHP5:
$resultArray = explode(" ", $sentence);
first. use explode on space. Then, count each part + the total assembled string and if it doesn't go over the limit you concat it onto the string with a space.
Try using explode() function.
In your case:
$expl = explode(" ",$sentence);
You'll get your sentence in an array. First word will be $expl[0], second - $expl[1] and so on. To print it out on the screen use:
$n = 10 //words to print
for ($i=0;$i<=$n;$i++) {
print $expl[$i]." ";
}
Create a function that you can re-use at any time. This will look for the last space if the given string's length is greater than the amount of characters you want to trim.
function niceTrim($str, $trimLen) {
$strLen = strlen($str);
if ($strLen > $trimLen) {
$trimStr = substr($str, 0, $trimLen);
return substr($trimStr, 0, strrpos($trimStr, ' '));
}
return $str;
}
$sentence = "this is a test sentence";
echo niceTrim($sentence, 12);
This will print
this is a
as required.
Hope this is the solution you are looking for!
this is just psudo code not php,
char[] sentence="your_sentence";
string new_constructed_sentence="";
string word="";
for(i=0;i<your_limit;i++){
character=sentence[i];
if(character==' ') {new_constructed_sentence+=word;word="";continue}
word+=character;
}
new_constructed_sentence is what you want!!!

Categories