break long string variable in multiple lines php [duplicate] - php

This question already has answers here:
How to split a long string without breaking words?
(4 answers)
Closed 7 years ago.
I created a variable which stores a very long string, and I want to print this variable in multiple lines.
$test ="This is some example text , I want to print this variable in 3 lines";
The output of the above $test would be
This is some example text,
I want to print this
variabale in 3 lines
Note: I want a new line after each 15 characters or each line have equal characters. I don't want to add break tag or any other tag during variable assignment.

CODEPAD
<?php
$str= 'This is some example text , I want to print this variable in 3 lines, also.';
$x = '12';
$array = explode( "\n", wordwrap( $str, $x));
var_dump($array);
?>
or use
$array = wordwrap( $str, $x, "\n");

Try this
<?php
$test ="This is some example text , I want to print this variable in 3 lines";
$array = str_split($test, 10);
echo implode("<br>",$array);
Based on this link
PHP: split a long string without breaking words
$longString = 'I like apple. You like oranges. We like fruit. I like meat, also.';
$arrayWords = explode(' ', $longString);
// Max size of each line
$maxLineLength = 18;
// Auxiliar counters, foreach will use them
$currentLength = 0;
$index = 0;
foreach($arrayWords as $word)
{
// +1 because the word will receive back the space in the end that it loses in explode()
$wordLength = strlen($word) + 1;
if( ( $currentLength + $wordLength ) <= $maxLineLength )
{
$arrayOutput[$index] .= $word . ' ';
$currentLength += $wordLength;
}
else
{
$index += 1;
$currentLength = $wordLength;
$arrayOutput[$index] = $word;
}
}

The easiest solution is to use wordwrap(), and explode() on the new line, like so:
$array = explode( "\n", wordwrap( $str, $x));
Where $x is a number of characters to wrap the string on.
Copied from here last comment

Try This
<?php
$test ="This is some example text , I want to print this variable in 3 lines";
$explode=explode(" ",$test);
$String='';
$newString='';
$maxCharacterCount=23;
foreach ($explode as $key => $value) {
$strlen=strlen($String);
if($strlen<=$maxCharacterCount){
$String.=' '.$value;
}else{
$newString.=$String.' '.$value.'<br>';
$String='';
}
}
$finalString= $newString.$String;
echo $finalString;
?>

OK now all is working. You just pass $string and #maxlenght in characters number and function returns table with cutted string.
don`t cut words,
don`t ever exeed maxLenght,
Only one thing to rember is that u need to care for comma usage i.e: "word, word".
$test ="This is some example text, I want to print this variable in 3 lines dasdas das asd asd asd asd asd ad ad";
function breakString($string, $maxLenght) {
//preparing string, getting lenght, max parts number and so on
$string = trim($string, ' ');
$stringLenght = strlen($string);
$parts = ($stringLenght / $maxLenght );
$finalPatrsNumber = ceil($parts);
$arrayString = explode(' ', $string);
//defining variables used to store data into a foreach loop
$partString ='';
$new = array();
$arrayNew = array();
/**
* go througt every word and glue it to a $partstring
*
* check $partstring lenght if it exceded $maxLenght
* then delete last word and pass it again to $partstring
* and create now array value
*/
foreach($arrayString as $word){
$partString.=$word.' ';
while( strlen( $partString ) > $maxLenght) {
$partString = trim($partString, ' ');
$new = explode(' ', $partString);
$partString = '';
$partString.= end($new).' ';
array_pop($new);
//var_dump($new);
if( strlen(implode( $new, ' ' )) < $maxLenght){
$value = implode( $new, ' ' );
$arrayNew[] = $value;
}
}
}
// /**
// * psuh last part of the string into array
// */
$string2 = implode(' ', $arrayNew);
$string2 = trim($string2, ' ');
$string2lenght = strlen($string2);
$newPart = substr($string, $string2lenght);
$arrayNew[] = $newPart;
/**
* return array with broken $parts of $string
* $party max lenght is < $maxlenght
* and breaks are only after words
*/
return $arrayNew;
}
/**
* sample usage
* #param string $string
* #param int $maxLenght Description
*/
foreach( breakString($test, 30) as $line){
echo $line."<br />";
}
displays:
This is some example text, I
want to print this variable
in 3 lines dasdas das asd asd
asd asd asd ad ad
btw. u can easly add here some rules like:
no single char in last row or don`t break on certain words and so on;

Related

how to get first two word from a sentence using php for loop

I am trying to get first two word from a sentence using php
$inp_val= "this is our country";
output will be : this is
// this input value has different string as Like: this, this is our, this name is mine
// i need to get only first two word or if anyone wrote only one word then i got same word but if any one wrote two or more word then it will collect only first two word..
I am trying with below code but it won't work properly..
$words = explode(' ', $inp_val);
$shop_name = "";
if (str_word_count($words) == 1) {
$shop_name .= mb_substr($words[0], 0, 1);
} else {
for ($i = 0; $i < 2; $i++) {
$w = $words[$i];
$shop_name .= mb_substr($w, 0, 1);
}
}
After exploding the input value by space (as you have done), you can use array_slice to extract the 2 first elements, then use the implode to concat the 2 elements as a string.
$inp_val = "this is our country";
$shop_name = implode(" ", array_slice(explode(' ', $inp_val), 0, 2));
echo $shop_name;
//OUTPUT: this is
This method that uses array_slice work well for one or more words

Saving values from a variable to an array

I have a long string variable that contains coordinates
I want to keep each coordinate in a separate cell in the array according to Lat and Lon..
For example. The following string:
string = "(33.110029967689556, 35.60865999564635), (33.093492845160036, 35.63955904349791), (33.0916232355565, 35.602995170206896)";
I want this:
arrayX[0] = "33.110029967689556";
arrayX[1] = "33.093492845160036";
arrayX[2] = "33.0916232355565";
arrayY[0] = "35.60865999564635";
arrayY[1] = "35.63955904349791";
arrayY[2] = "35.602995170206896";
Does anyone have an idea ?
Thanks
Use substr to modify sub string, it allow you to do that with a little line of code.
$array_temp = explode('),', $string);
$arrayX = [];
$arrayY = [];
foreach($array_temp as $at)
{
$at = substr($at, 1);
list($arrayX[], $arrayY[]) = explode(',', $at);
}
print_r($arrayX);
print_r($arrayY);
The simplest way is probably to use a regex to match each tuple:
Each number is a combination of digits and .: the regex [\d\.]+ matches that;
Each coordinate has the following format: (, number, ,, space, number,). The regex is \([\d\.]+,\s*[\d\.]+\).
Then you can capture each number by using parenthesis: \(([\d\.]+),\s*([\d\.]+)\). This will produce to capturing groups: the first will contain the X coordinate and the second the Y.
This regex can be used with the method preg_match_all.
<?php
$string = '(33.110029967689556, 35.60865999564635), (33.093492845160036, 35.63955904349791), (33.0916232355565, 35.602995170206896)';
preg_match_all('/\(([\d\.]+)\s*,\s*([\d\.]+)\)/', $string, $matches);
$arrayX = $matches['1'];
$arrayY = $matches['2'];
var_dump($arrayX);
var_dump($arrayY);
For a live example see http://sandbox.onlinephpfunctions.com/code/082e8454486dc568a6557058fef68d6f10c8dbd0
My suggestion, working example here: https://3v4l.org/W99Uu
$string = "(33.110029967689556, 35.60865999564635), (33.093492845160036, 35.63955904349791), (33.0916232355565, 35.602995170206896)";
// Split by each X/Y pair
$array = explode("), ", $string);
// Init result arrays
$arrayX = array();
$arrayY = array();
foreach($array as $pair) {
// Remove parentheses
$pair = str_replace('(', '', $pair);
$pair = str_replace(')', '', $pair);
// Split into two strings
$arrPair = explode(", ", $pair);
// Add the strings to the result arrays
$arrayX[] = $arrPair[0];
$arrayY[] = $arrPair[1];
}
You need first to split the string into an array. Then you clean the value to get only the numbers. Finally, you put the new value into the new array.
<?php
$string = "(33.110029967689556, 35.60865999564635), (33.093492845160036, 35.63955904349791), (33.0916232355565, 35.602995170206896)";
$loca = explode(", ", $string);
$arr_x = array();
$arr_y = array();
$i = 1;
foreach($loca as $index => $value){
$i++;
if ($i % 2 == 0) {
$arr_x[] = preg_replace('/[^0-9.]/', '', $value);
}else{
$arr_y[] = preg_replace('/[^0-9.]/', '', $value);
}
}
print_r($arr_x);
print_r($arr_y);
You can test it here :
http://sandbox.onlinephpfunctions.com/code/4bf04e7aabeba15ecfa114d8951eb771610a43a4

PHP New Line after n commas

I want to insert a new line after n commas.
For example I got this value: 385,386,387,388,389,390,391,392,393,394,395,396,397,398,399,400,401,402,403,404,405,406,407,408,409,410,411,412,413,414,415,416,417,418,419,420,421,422,423,424,425,426
How I could echo them all, but every 5th comma there should be a linebreak?
385,386,387,388,389,
390,391,392,393,394,
395,396,397,398,399,
400,401,402,403,404,
405,406,407,408,409,
410,411,412,413,414,
415,416,417,418,419,
420,421,422,423,424,
425,426
Here's one method:
// Get all numbers
$numbers = explode(',', $str);
// Split into groups of 5 (n)
$lines = array_chunk($numbers, 5);
// Format each line as comma delimited
$formattedLines = array_map(function ($row) { return implode(',', $row); }, $lines);
// Format groups into new lines with commas at the end of each line (except the last)
$output = implode(",\n", $formattedLines);
Try this
<?php
//Start //Add this code if your values in string like that
$string = "385,386,387,388,389,390,391,392,393,394,395,396,397,398,399,400,401,402,403,404,405,406,407,408,409,410,411,412,413,414,415,416,417,418,419,420,421,422,423,424,425,426";
$string_array = explode(',', $string);
//End //Add this code if your values in string like that
//If you have values in array then direct use below code skip above code and replace $string_array variable with yours
end($string_array);
$last = key($string_array);
foreach ($string_array as $key => $value) {
if($last==$key){
echo $value;
}else{
echo $value.',';
}
if(($key+1)%5==0){
echo "<br />";
}
}
?>
Try like this.
You can explode the string with commas and check for every 5th
position there should be a line break.
You can check it with dividing key with 5.(i.e) it will give you a
remainder of 0
Please note that key starts from 0, so I have added (key+1), to make it start from 1
$string = "385,386,387,388,389,390,391,392,393,394,395,396,397,398,399,400,401,402,403,404,405,406,407,408,409,410,411,412,413,414,415,416,417,418,419,420,421,422,423,424,425,426";
$stringexplode = explode(",", $string);
$countstringexplode = count($stringexplode);
foreach($stringexplode as $key => $val)
{
$keyIncrement = $key+1;
echo $val.($countstringexplode == $keyIncrement ? "" : ",") ;
if(($keyIncrement) % 5 == 0)
echo "<br>";
}
?>

Change one of the array value if it equals to something

I'm using explode() php function to divide the sentence and turn it into array the user had filled in the input field on different page. From that sentence I need to find if there is that word and if it is in it add <b></b> around of that word. I've tried:
$wordsentence = explode(' ', $wordsentence);
$place == '0';
foreach ($wordsentence as $ws) {
if ($ws == $word) {
$word = '<b>'.$word.'</b>';
$save = $place;
}
$place++;
}
but there might be more than one word in the same sentence. Is there any way to mark multiple words?
You initial setup:
$wordSentence = "This is a sentence, made up of words";
$wordTest = "made";
$wordsArr = explode(' ', $wordSentence);
I swapped out the foreach loop for a standard for loop, this way we don't need to initialize a separate index variable and keep track of it.
for ($i = 0; $i < count($wordsArr); $i++) {
if ($wordsArr[$i] == $wordTest) {
$boldWord = '<b>' . $wordTest . '</b>';
//take your wordsArray, at the current index,
//swap out the old version with the bold version
array_splice($wordsArr, $i, 1, $boldWord);
}
}
And to complete our test:
$boldedSentence = implode(' ', $wordsArr);
echo $boldedSentence . "\n";
Output:
> This is a sentence, <b>made</b> up of words

How remove the last comma in my string?

I've been trying to figgure out using substr, rtrim and it keeps removing all the commas. And if it doesn't nothing shows up. So I am basicly stuck and require some help.. Would've been apriciated.
if(is_array($ids)) {
foreach($ids as $id) {
$values = explode(" ", $id);
foreach($values as $value) {
$value .= ', ';
echo ltrim($value, ', ') . '<br>';
}
}
}
I am guessing that you are trying to take an array of strings of space separated ids and flatten it into a comma separated list of the ids.
If that is correct you can do it as:
$arr = [
'abc def ghi',
'jklm nopq rstu',
'vwxy',
];
$list = implode(', ', explode(' ', implode(' ', $arr)));
echo $list;
output:
abc, def, ghi, jklm, nopq, rstu, vwxy
Change ltrim by rtrim:
ltrim — Strip whitespace (or other characters) from the beginning of a string
rtrim — Strip whitespace (or other characters) from the end of a string
<?php
$ids = Array ( 1,2,3,4 );
$final = '';
if(is_array($ids)) {
foreach($ids as $id) {
$values = explode(" ", $id);
foreach($values as $value) {
$final .= $value . ', ';
}
}
echo rtrim($final, ', ') . '<br>';
echo substr($final, 0, -2) . '<br>'; //other solution
}
?>
If your array looks like;
[0] => 1,
[1] => 2,
[2] => 3,
...
The following should suffice (not the most optimal solution);
$string = ''; // Create a variable to store our future string.
$iterator = 0; // We will need to keep track of the current array item we are on.
if ( is_array( $ids ) )
{
$array_length = count( $ids ); // Store the value of the arrays length
foreach ( $ids as $id ) // Loop through the array
{
$string .= $id; // Concat the current item with our string
if ( $iterator >= $array_length ) // If our iterator variable is equal to or larger than the max value of our array then break the loop.
break;
$string .= ", "; // Append the comma after our current item.
$iterator++; // Increment our iterator variable
}
}
echo $string; // Outputs "1, 2, 3..."
Use trim() function.
Well, if you have a string like this
$str="foo, bar, foobar,";
use this code to remove the Last comma
<?Php
$str="foo, bar, foobar,";
$string = trim($str, " ,");
echo $string;
output: foo, bar, foobar

Categories