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>";
Related
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
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 :)
$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 am trying to create a program which determines if a string is a palindrome or not.
This is the error i'm getting.
Notice: Array to string conversion in C:\wamp\www\task18.php on line 22
My code is below:
<?php
//TASK 18 PALINDROME
//use string split function to split a string into an array
$str = "Mum";
$str =strtolower($str);
$strArray = array();
$strArray = str_split($str);
$len = sizeof($strArray);
$reverseStr ="";
for($i=$len-1; $i>=0; $i--){
$reverseStr .=$strArray[$i];
}
if ($strArray == $reverseStr) {
echo " $strArray is a palindrome";
} else {
echo " $strArray is not a palindrome";
}
First of all, you're comparing a string ($reverseStr) to an array ($strArray).
You need to edit the code to this:
for($i=$len-1; $i>=0; $i--){
$reverseStr[] .=$strArray[$i];
}
This will then put the reversed word into an array. So mum would be correctly outputted as mum, and test would be tset, but in an array.
This will then make the if pass, but you can't echo an array, so you should just echo out $str.
Full code:
$str = "mum";
$str =strtolower($str);
$strArray = array();
$strArray = str_split($str);
$len = sizeof($strArray);
$reverseStr = array();
for($i=$len-1; $i>=0; $i--){
$reverseStr[] .=$strArray[$i];
}
if ($strArray == $reverseStr) {
echo "$str is a palindrome";
} else {
echo "$str is not a palindrome";
}
or if you need to use $strArray to be in the echo, you can use implode():
echo implode($strArray). " is/is not a palindrome";
If you want to make it shorter, you can use this:
$str = strtolower("Mum");
$strArray = str_split($str);
$len = sizeof($strArray);
$reverseStr = array();
for($i=$len-1; $i>=0; $i--)
$reverseStr[] .=$strArray[$i];
echo "$str is ".($strArray==$reverseStr ? "" : "not") . " a palindrome";
Description:- You can't Echo an array that's why you are getting this error.Because you are echoing a array which is not possible.Type Juggling(Variables are some time automatically cast to best fit).That's same happens with your code because you trying to echo a array and when php trying to convert it to string it fails.Here below is a code to check palidrome using str_split().
<?php
$word = strtolower("mum");
$splitted = str_split($word);
$reversedWord = "";
$length = strlen($word);
for($i = 0; $i < $length; $i++)
$reversedWord .= $splitted[$length - $i - 1];
echo $word == $reversedWord ? "It's a palindrome " : "It's not a palindrome";
?>
you can also use given thing without using any php function.
$str="level";
for($i=0;$i<40000;$i++)
if($str[$i])
$count++;
else
break;
for ($j=$count;$j >=0; $j--){
$newStr.=$str[$j];
}
//echo $newStr;
if($newStr==$str)
echo $newStr." is a palindrome";
else
echo $newStr." is not a palindrome";
?>
You might want to try this, it works...
function fn_palindrome($palindrome) {
$reversed = '';
$original = $palindrome;
$string = array(); $j = 0;
$converted = (string) $palindrome;
$palindrome = str_split($converted);
$i = count($palindrome) - 1;
while($i >= 0) {
$string[$j] = $palindrome[$i];
$j++; $i--;
}
$reversed = implode('', $string);
if($reversed == $original) {
return TRUE;
} else {
return FALSE;
}
}
Assume I have a string variable:
$str = "abcdefghijklmn";
What is the best way in PHP to write a function to start at the end of the string, and return every other character? The output from the example should be:
nljhfdb
Here is what I have so far:
$str = "abcdefghijklmn";
$pieces = str_split(strrev($str), 1);
$return = null;
for($i = 0; $i < sizeof($pieces); $i++) {
if($i % 2 === 0) {
$return .= $pieces[$i];
}
}
echo $return;
Just try with:
$input = 'abcdefghijklmn';
$output = '';
for ($i = strlen($input) - 1; $i >= 0; $i -= 2) {
$output .= $input[$i];
}
Output:
string 'nljhfdb' (length=7)
You need to split the string using str_split to store it in an array. Now loop through the array and compare the keys to do a modulo operation.
<?php
$str = "abcdefghijklmn";
$nstr="";
foreach(str_split(strrev($str)) as $k=>$v)
{
if($k%2==0){
$nstr.= $v;
}
}
echo $nstr; //"prints" nljhfdb
I'd go for the same as Shankar did, though this is another approach for the loop.
<?php
$str = "abcdefghijklmn";
for($i=0;$i<strlen($str);$i++){
$res .= (($i-1) % 2 == 0 ? $str[$i] : "");
}
print(strrev($res)); // Result: nljhfdb
?>
reverse the string then do something like
foreach($array as $key => $value)
{
if($key%2 != 0) //The key is uneven, skip
continue;
//do your stuff
}
loop forward, append backward
<?php
$res = '';
$str = "abcdefghijklmn";
for ($i = 0; $i < strlen($str); $i++) {
if(($i - 1) % 2 == 0)
$res = $str[$i] . $res;
}
echo $res;
?>
preg_replace('/(.)./', '$1', strrev($str));
Where preg_replace replaces every two characters of the reversed string with the first of the two.
How about something like this:
$str = str_split("abcdefghijklmn");
echo join("",
array_reverse(
array_filter($str, function($var) {
global $str;
return(array_search($var,$str) & 1);
}
)
)
);