PHP - Split String Into Arrays for every N characters - php

Is it possible to take a very long string and split it by sentence into 5000 char (or smaller) array items?
Here's what I have so far:
<?php
$text = 'VERY LONG STRING';
foreach(explode('. ', $text) as $chunk) {
$accepted[] = $chunk;
}
?>
This just splits the string into an array containing single sentence items. I need to group items into sub arrays, each containing a list of items which, when added together, contain no more than 5000 characters.
I tried this:
<?php
$text = 'VERY LONG STRING';
foreach(explode('. ', $text) as $chunk) {
$key = strlen(implode('. ', $accepted).'. '.$chunk) / 5000;
$accepted[$key][] = $chunk;
}
?>
You can probably see what I tried to do here, but it didn't work.
UPDATE:
This did the trick:
<?php
foreach(explode('. ', $text) as $chunk) {
$chunkLen = strlen(implode('. ', $result).'. '.$chunk.'.');
if ($len + $chunkLen > 5000) {
$result[] = $partial;
$partial = [];
$len = 0;
}
$len += $chunkLen;
$partial[] = $chunk;
}
if($partial) $result[] = $partial;
?>
Thank you to everyone who responded, your support means a lot.

You could do something like this:
$text = 'VERY LONG STRING';
$result = [];
$partial = [];
$len = 0;
foreach(explode(' ', $text) as $chunk) {
$chunkLen = strlen($chunk);
if ($len + $chunkLen > 5000) {
$result[] = $partial;
$partial = [];
$len = 0;
}
$len += $chunkLen;
$partial[] = $chunk;
}
if ($partial) {
$result[] = $partial;
}
You can test it more easily if you do it with a lower max length

If I don't misunderstand your question then you need something like this,
<?php
$text = 'VERY LONG STRING';
$s = chunk_split($text, 3, '|'); // put 5000 instead of 3
$s = substr($s, 0, -1);
$accepted = explode('|', $s);
print_r($accepted);
?>
OR
<?php
$text = 'VERY LONG STRING';
$accepted = str_split($text, 3);
print_r($accepted);
?>
DEMO: https://3v4l.org/H9DAl
DEMO: https://3v4l.org/PN7Aj

Related

How can I split the string in php?

I have a string like $str.
$str = "00016cam 321254300022cam 321254312315300020cam 32125433153";
I want to split it in array like this. The numbers before 'cam' is the string length.
$splitArray = ["00016cam 3212543", "00022cam 3212543123153", "00020cam 32125433153"]
I have tried following code:
$lengtharray = array();
while ($str != null)
{
$sublength = substr($str, $star, $end);
$star += (int)$sublength; // echo $star."<br>"; // echo $sublength."<br>";
if($star == $total)
{
exit;
}
else
{
}
array_push($lengtharray, $star); // echo
print_r($lengtharray);
}
You can try this 1 line solution
$str = explode('**', preg_replace('/\**cam/', 'cam', $str)) ;
If your string doesn't contain stars then I'm afraid you need to write a simple parser that will:
take characters from the left until it's not numeric
do substr having the length
repeat previous steps on not consumed string
<?php
$input = "00016cam 321254300022cam 321254312315300020cam 32125433153";
function parseArray(string $input)
{
$result = [];
while ($parsed = parseItem($input)) {
$input = $parsed['rest'];
$result[] = $parsed['item'];
}
return $result;
}
function parseItem(string $input)
{
$sLen = strlen($input);
$len = '';
$pos = 0;
while ($pos < $sLen && is_numeric($input[$pos])) {
$len .= $input[$pos];
$pos++;
}
if ((int) $len == 0) {
return null;
}
return [
'rest' => substr($input, $len),
'item' => substr($input, 0, $len)
];
}
var_dump(parseArray($input));
this code works for me. hope helps.
$str = "**00016**cam 3212543**00022**cam 3212543123153**00020**cam 32125433153";
$arr = explode("**", $str);
for ($i=1; $i < sizeof($arr); $i=$i+2)
$arr_final[]=$arr[$i].$arr[$i+1];

How do I output a duplicate letter in a string line?

I have string like $text = '1234567812349101'; I want to be able to output the repeated letters and how many times they're repeated. For example the expected result should be This string 1234 is repeated. Repeated 1 times.
I've tried:
$text = '1234567812349101';
$disp = str_split($text, 4);
foreach ($disp as $char) {
if (preg_match('/(.{4,})\\1{2,}/', $char)) {
echo "This string $char is repeated. Repeated times.";
}
}
But there's no output.
How can I do this?
Try using array_count_values:
$text = '1234567812349101';
$disp = str_split($text, 4);
$dupes = array_filter(array_count_values($disp), function ($el) {
return ($el > 1);
});
foreach ($dupes as $dupe => $times) {
echo "This string $dupe is repeated. Repeated " . ($times - 1) . " times.\n";
}
Output:
This string 1234 is repeated. Repeated 1 times.
eval.in demo
$text = '1234567812349101';
$disp = str_split($text, 4);
$count = 0;
foreach($disp as $char){
if(strcmp("1234",$char)){
$count++;
}
}
$cnt = $count-1;
if($cnt > 1){
echo "1234 String is repeated. Repeated ".$cnt."times";
}
I hope This will help you out :)

Separate alphabets and numbers from a string

$str = 'ABC300';
How I can get values like
$alphabets = "ABC";
$numbers = 333;
I have a idea , first remove numbers from the string and save in a variable. then remove alphabets from the $str variable and save. try the code
$str = 'ABC300';
$alf= trim(str_replace(range(0,9),'',$str));//removes number from the string
$number = preg_replace('/[A-Za-z]+/', '', $str);// removes alphabets from the string
echo $alf,$number;// your expected output
Try something like this (it's not that fast)...
$string = "ABCDE3883475";
$numbers = "";
$alphabets = "";
$strlen = strlen($string);
for($i = 0; $i <= $strlen; $i++) {
$char = substr($string, $i, 1);
if(is_numeric($char)) {
$numbers .= $char;
} else {
$alphabets .= $char;
}
}
Then all numbers should be in $numbers and all alphabetical characters should be in $alphabets ;)
https://3v4l.org/Xh4FR
A way to do that is to find all digits and use the array to replace original string with the digits inside.
For example
function extractDigits($string){
preg_match_all('/([\d]+)/', $string, $match);
return $match[0];
}
$str = 'abcd1234ab12';
$digitsArray = extractDigits($str);
$allAlphas = str_replace($digitsArray,'',$str);
$allDigits = '';
foreach($digitsArray as $digit){
$allDigits .= $digit;
}

I want to filter a string and to make an array using php

This is my sample string (this one has five words; in practice, there may be more):
$str = "I want to filter it";
Output that I want:
$output[1] = array("I","want","to","filter","it");
$output[2] = array("I want","want to","to filter","filter it");
$output[3] = array("I want to","want to filter","to filter it");
$output[4] = array("I want to filter","want to filter it");
$output[5] = array("I want to filter it");
What I am trying:
$text = trim($str);
$text_exp = explode(' ',$str);
$len = count($text_exp);
$output[$len][] = $text; // last element
$output[1] = $text_exp; // first element
This gives me the first and the last arrays. How can I get all the middle arrays?
more generic solution that works with any length word:
$output = array();
$terms = explode(' ',$str);
for ($i = 1; $i <= count($terms); $i++ )
{
$round_output = array();
for ($j = 0; $j <= count($terms) - $i; $j++)
{
$round_output[] = implode(" ", array_slice($terms, $j, $i));
}
$output[] = $round_output;
}
You can do that easily with regular expressions that give you the most flexibility. See below for the way that supports dynamic string length and multiple white characters between words and also does only one loop which should make it more efficient for long strings..
<?php
$str = "I want to filter it";
$count = count(preg_split("/\s+/", $str));
$results = [];
for($i = 1; $i <= $count; ++$i) {
$expr = '/(?=((^|\s+)(' . implode('\s+', array_fill(0, $i, '[^\s]+')) . ')($|\s+)))/';
preg_match_all($expr, $str, $matches);
$results[$i] = $matches[3];
}
print_r($results);
You can use a single for loop and if conditions to do
$str = "I want to filter it";
$text = trim($str);
$text_exp = explode(' ',$str);
$len = count($text_exp);
$output1=$text_exp;
$output2=array();
$output3=array();
$output4=array();
$output5=array();
for($i=0;$i<count($text_exp);$i++)
{
if($i+1<count($text_exp) && $text_exp[$i+1]!='')
{
$output2[]=$text_exp[$i].' '.$text_exp[$i+1];
}
if($i+2<count($text_exp) && $text_exp[$i+2]!='')
{
$output3[]=$text_exp[$i].' '.$text_exp[$i+1].' '.$text_exp[$i+2];
}
if($i+3<count($text_exp) && $text_exp[$i+3]!='')
{
$output4[]=$text_exp[$i].' '.$text_exp[$i+1].' '.$text_exp[$i+2].' '.$text_exp[$i+3];
}
if($i+4<count($text_exp) && $text_exp[$i+4]!='')
{
$output5[]=$text_exp[$i].' '.$text_exp[$i+1].' '.$text_exp[$i+2].' '.$text_exp[$i+3].' '.$text_exp[$i+4];
}
}

Cut-off a string after the fourth line-break

I've got the problem, that I want to cut-off a long string after the fourth line-break and have it continue with "..."
<?php
$teststring = "asddsadsadsadsaa\n
asddsadsadsadsaa\n
asddsadsadsadsaa\n
asddsadsadsadsaa\n
asddsadsadsadsaa\n
asddsadsadsadsaa\n";
?>
should become:
<?php
$teststring = "asddsadsadsadsaa\n
asddsadsadsadsaa\n
asddsadsadsadsaa\n
asddsadsadsadsaa...";
?>
I know how to break the string after the first \n but I don't know how to do it after the fourth.
I hope you can help me.
you can explode the string and then take all the parts you need
$newStr = ""; // initialise the string
$arr = explode("\n", $teststring);
if(count($arr) > 4) { // you've got more than 4 line breaks
$arr = array_splice($arr, 0, 4); // reduce the lines to four
foreach($arr as $line) { $newStr .= $line; } // store them all in a string
$newStr .= "...";
} else {
$newStr = $teststring; // there was less or equal to four rows so to us it'all ok
}
echo preg_replace ('~((.*?\x0A){4}).*~s', '\\1...', $teststring);
Something like this ?
$teststring = "asddsadsadsadsaa
asddsadsadsadsaa
asddsadsadsadsaa
asddsadsadsadsaa
asddsadsadsadsaa
asddsadsadsadsaa";
$e = explode("\n", $teststring);
if (count($e) > 4)
{
$finalstring = "";
for ($i = 0; $i < 4; $i++)
{
$finalstring.= $e[$i];
}
}
else
{
$finalstring = $teststring;
}
echo "<pre>$finalstring</pre>";

Categories