Add space after every 4th character - php

I want to add a space to some output after every 4th character until the end of the string.
I tried:
$str = $rows['value'];
<? echo substr($str, 0, 4) . ' ' . substr($str, 4); ?>
Which just got me the space after the first 4 characters.
How can I make it show after every 4th ?

You can use chunk_split [docs]:
$str = chunk_split($rows['value'], 4, ' ');
DEMO
If the length of the string is a multiple of four but you don't want a trailing space, you can pass the result to trim.

Wordwrap does exactly what you want:
echo wordwrap('12345678' , 4 , ' ' , true )
will output:
1234 5678
If you want, say, a hyphen after every second digit instead, swap the "4" for a "2", and the space for a hyphen:
echo wordwrap('1234567890' , 2 , '-' , true )
will output:
12-34-56-78-90
Reference - wordwrap

Have you already seen this function called wordwrap?
http://us2.php.net/manual/en/function.wordwrap.php
Here is a solution. Works right out of the box like this.
<?php
$text = "Thiswordissoverylong.";
$newtext = wordwrap($text, 4, "\n", true);
echo "$newtext\n";
?>

Here is an example of string with length is not a multiple of 4 (or 5 in my case).
function space($str, $step, $reverse = false) {
if ($reverse)
return strrev(chunk_split(strrev($str), $step, ' '));
return chunk_split($str, $step, ' ');
}
Use :
echo space("0000000152748541695882", 5);
result: 00000 00152 74854 16958 82
Reverse mode use ("BVR code" for swiss billing) :
echo space("1400360152748541695882", 5, true);
result: 14 00360 15274 85416 95882
EDIT 2021-02-09
Also useful for EAN13 barcode formatting :
space("7640187670868", 6, true);
result : 7 640187 670868
short syntax version :
function space($s=false,$t=0,$r=false){return(!$s)?false:(($r)?trim(strrev(chunk_split(strrev($s),$t,' '))):trim(chunk_split($s,$t,' ')));}
Hope it could help some of you.

On way would be to split into 4-character chunks and then join them together again with a space between each part.
As this would technically miss to insert one at the very end if the last chunk would have exactly 4 characters, we would need to add that one manually (Demo):
$chunk_length = 4;
$chunks = str_split($str, $chunk_length);
$last = end($chunks);
if (strlen($last) === $chunk_length) {
$chunks[] = '';
}
$str_with_spaces = implode(' ', $chunks);

one-liner:
$yourstring = "1234567890";
echo implode(" ", str_split($yourstring, 4))." ";
This should give you as output:
1234 5678 90
That's all :D

The function wordwrap() basically does the same, however this should work as well.
$newstr = '';
$len = strlen($str);
for($i = 0; $i < $len; $i++) {
$newstr.= $str[$i];
if (($i+1) % 4 == 0) {
$newstr.= ' ';
}
}

PHP3 Compatible:
Try this:
$strLen = strlen( $str );
for($i = 0; $i < $strLen; $i += 4){
echo substr($str, $i, 4) . ' ';
}
unset( $strLen );

StringBuilder str = new StringBuilder("ABCDEFGHIJKLMNOP");
int idx = str.length() - 4;
while (idx > 0){
str.insert(idx, " ");
idx = idx - 4;
}
return str.toString();
Explanation, this code will add space from right to left:
str = "ABCDEFGH" int idx = total length - 4; //8-4=4
while (4>0){
str.insert(idx, " "); //this will insert space at 4th position
idx = idx - 4; // then decrement 4-4=0 and run loop again
}
The final output will be:
ABCD EFGH

Related

PHP: Shift characters of string by 5 spaces? So that A becomes F, B becomes G etc

How can I shift characters of string in PHP by 5 spaces?
So say:
A becomes F
B becomes G
Z becomes E
same with symbols:
!##$%^&*()_+
so ! becomes ^
% becomes )
and so on.
Anyway to do this?
The other answers use the ASCII table (which is good), but I've got the impression that's not what you're looking for. This one takes advantage of PHP's ability to access string characters as if the string itself is an array, allowing you to have your own order of characters.
First, you define your dictionary:
// for simplicity, we'll only use upper-case letters in the example
$dictionary = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
Then you go through your input string's characters and replace each of them with it's $position + 5 in the dictionary:
$input_string = 'STRING';
$output_string = '';
$dictionary_length = strlen($dictionary);
for ($i = 0, $length = strlen($input_string); $i < $length; $i++)
{
$position = strpos($dictionary, $input_string[$i]) + 5;
// if the searched character is at the end of $dictionary,
// re-start counting positions from 0
if ($position > $dictionary_length)
{
$position = $position - $dictionary_length;
}
$output_string .= $dictionary[$position];
}
$output_string will now contain your desired result.
Of course, if a character from $input_string does not exist in $dictionary, it will always end up as the 5th dictionary character, but it's up to you to define a proper dictionary and work around edge cases.
Iterate over characters and, get ascii value of each character and get char value of the ascii code shifted by 5:
function str_shift_chars_by_5_spaces($a) {
for( $i = 0; $i < strlen($a); $i++ ) {
$b .= chr(ord($a[$i])+5);};
}
return $b;
}
echo str_shift_chars_by_5_spaces("abc");
Prints "fgh"
Iterate over string, character at a time
Get character its ASCII value
Increase by 5
Add to new string
Something like this should work:
<?php
$newString = '';
foreach (str_split('test') as $character) {
$newString .= chr(ord($character) + 5);
}
echo $newString;
Note that there is more than one way to iterate over a string.
PHP has a function for this; it's called strtr():
$shifted = strtr( $string,
"ABCDEFGHIJKLMNOPQRSTUVWXYZ",
"FGHIJKLMNOPQRSTUVWXYZABCDE" );
Of course, you can do lowercase letters and numbers and even symbols at the same time:
$shifted = strtr( $string,
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!##$%^&*()_+",
"FGHIJKLMNOPQRSTUVWXYZABCDEfghijklmnopqrstuvwxyzabcde5678901234^&*()_+!##$%" );
To reverse the transformation, just swap the last two arguments to strtr().
If you need to change the shift distance dynamically, you can build the translation strings at runtime:
$shift = 5;
$from = $to = "";
$sequences = array( "ABCDEFGHIJKLMNOPQRSTUVWXYZ", "abcdefghijklmnopqrstuvwxyz",
"0123456789", "!##$%^&*()_+" );
foreach ( $sequences as $seq ) {
$d = $shift % strlen( $seq ); // wrap around if $shift > length of $seq
$from .= $seq;
$to .= substr($seq, $d) . substr($seq, 0, $d);
}
$shifted = strtr( $string, $from, $to );

Convert numbers to time, or in other words, insert : in the middle of a string

how would I be able to inser a : in the middle of numbers like 840 or 1530. I basically want to add a : at the third last position, as I got some strings with 3 and some with 4 numbers in it.
Thanks!
Try this:
$x = '1930';
echo substr($x, 0, strlen($x) - 2) . ':' . substr($x, strlen($x) - 2);
Here is another way:
<?php
$int = 1530;
$str = (string) $int;
$newstring = substr_replace($str, ':', 3, 0);
echo $newstring;
?>

Fill the remainder of a string with blank spaces

I have a string with, for example, 32 characters. For first, i want to establish that the string have max 32 characters and i want add blank spaces if characters is only, for example, 9.
Example:
ABCDEFGHI ---> 9 characters
I want this:
ABCDEFGHI_______________________ ---> 9 characters + 23 blank spaces added automatically.
The function you are looking for is str_pad.
http://php.net/manual/de/function.str-pad.php
$str = 'ABCDEFGHI';
$longstr = str_pad($str, 32);
The default pad string already is blank spaces.
As your maximum length should be 32 and str_pad won't take any action when the string is longer than 32 characters you might want to shorten it down using substr then:
http://de.php.net/manual/de/function.substr.php
$result = substr($longstr, 0, 32);
This again won't take any action if your string is exactly 32 characters long, so you always end up with a 32 characters string in $result now.
Use str_pad:
str_pad('ABCDEFGHI', 32);
Use str_pad function:
$result = str_pad($input, 32, " ");
you need str_pad
$padded = str_pad($in,32,' ');
You can have left or right padded, tons of options, check them all out here
If the input exceeds 32 chars, no action is taken, but that's an easy check to implement:
if (strlen($padded) > 32)
{
throw new Exception($padded.' is too long');//or some other action
}
If you want to do more customization inside the function you could use this
function fill($input, $length, $filler = ' ')
{
$len = strlen($input);
$diff = $length - $len;
if($diff > 0)
{
for ($i = 0; $i < $diff; $i++)
{
$input = $input . $filler;
}
}
return substr($input, 0, $length);
}
for($i=0;$i<(32-strlen($your_string));$i++)
{
$new_string.=$your_string.' '
}
hope that would be helpful for you
$str = "ABCDEFGHI";
for ($i = 0; $i < 23; $i++) {
$str .= " ";
}
This is what You want?
When saw other comments, then that will be the best solution.

PHP Word Length Density / Count calc for a string

Given a text, how could I count the density / count of word lengths, so that I get an output like this
1 letter words : 52 / 1%
2 letter words : 34 / 0.5%
3 letter words : 67 / 2%
Found this but for python
counting the word length in a file
Index by word length
You could start by splitting your text into words, using either explode() (as a very/too simple solution) or preg_split() (allows for stuff that's a bit more powerful) :
$text = "this is some kind of text with several words";
$words = explode(' ', $text);
Then, iterate over the words, getting, for each one of those, its length, using strlen() ; and putting those lengths into an array :
$results = array();
foreach ($words as $word) {
$length = strlen($word);
if (isset($results[$length])) {
$results[$length]++;
}
else {
$results[$length] = 1;
}
}
If you're working with UTF-8, see mb_strlen().
At the end of that loop, $results would look like this :
array
4 => int 5
2 => int 2
7 => int 1
5 => int 1
The total number of words, which you'll need to calculate the percentage, can be found either :
By incrementing a counter inside the foreach loop,
or by calling array_sum() on $results after the loop is done.
And for the percentages' calculation, it's a bit of maths -- I won't be that helpful, about that ^^
You could explode the text by spaces and then for each resulting word, count the number of letters. If there are punctuation symbols or any other word separator, you must take this into account.
$lettercount = array();
$text = "lorem ipsum dolor sit amet";
foreach (explode(' ', $text) as $word)
{
#$lettercount[strlen($word)]++; // # for avoiding E_NOTICE on first addition
}
foreach ($lettercount as $numletters => $numwords)
{
echo "$numletters letters: $numwords<br />\n";
}
ps: I have not proved this, but should work
You can be smarter about removing punctuation by using preg_replace.
$txt = "Sean Hoare, who was first named News of the World journalist to make hacking allegations, found dead at Watford home. His death is not being treated as suspiciou";
$txt = str_replace( " ", " ", $txt );
$txt = str_replace( ".", "", $txt );
$txt = str_replace( ",", "", $txt );
$a = explode( " ", $txt );
$cnt = array();
foreach ( $a as $b )
{
if ( isset( $cnt[strlen($b)] ) )
$cnt[strlen($b)] += 1;
else
$cnt[strlen($b)] = 1;
}
foreach ( $cnt as $k => $v )
{
echo $k . " letter words: " . $v . " " . round( ( $v * 100 ) / count( $a ) ) . "%\n";
}
My simple way to limit the number of words characters in some string with php.
function checkWord_len($string, $nr_limit) {
$text_words = explode(" ", $string);
$text_count = count($text_words);
for ($i=0; $i < $text_count; $i++){ //Get the array words from text
// echo $text_words[$i] ; "
//Get the array words from text
$cc = (strlen($text_words[$i])) ;//Get the lenght char of each words from array
if($cc > $nr_limit) //Check the limit
{
$d = "0" ;
}
}
return $d ; //Return the value or null
}
$string_to_check = " heare is your text to check"; //Text to check
$nr_string_limit = '5' ; //Value of limit len word
$rez_fin = checkWord_len($string_to_check,$nr_string_limit) ;
if($rez_fin =='0')
{
echo "false";
//Execute the false code
}
elseif($rez_fin == null)
{
echo "true";
//Execute the true code
}
?>

PHP function to loop thru a string and replace characters for all possible combinations

I am trying to write a function that will replace characters in a string with their HTML entity encoded equivalent.
I want it to be able to go through all the possible combinations for the given string, for example:
go one-by-one
then combo i.e.. 2 at a time, then three at a time, till you get length at a time
then start in combo split, i.e.. first and last, then first and second to last
then first and last two, fist and second/third last
So for the characters "abcd" it would return:
abcd
abcd
abcd
abcd
abcd
abcd
abcd
abcd
abcd
abcd
abcd
abcd
etc.......... so on and so forth till there are no other combinations
Any ideas, or has anyone seen a function somewhere I could modify for this purpose?
loop from 0 to 2^length - 1. On each step, if Nth bit of the loop counter is 1, encode the Nth character
$str = 'abcd';
$len = strlen($str);
for($i = 0; $i < 1 << $len; $i++) {
$p = '';
for($j = 0; $j < $len; $j++)
$p .= ($i & 1 << $j) ? '&#' . ord($str[$j]) . ';' : $str[$j];
echo $p, "\n";
}
There are 2^n combinations, so this will get huge fast. This solution will only work as long as it fits into PHP's integer size. But really who cares? A string that big will print so many results you'll spend your entire life looking at them.
<?php
$input = 'abcd';
$len = strlen($input);
$stop = pow(2, $len);
for ($i = 0; $i < $stop; ++$i)
{
for ($m = 1, $j = 0; $j < $len; ++$j, $m <<= 1)
{
echo ($i & $m) ? '&#'.ord($input[$j]).';' : $input[$j];
}
echo "\n";
}
How about this?
<?php
function permutations($str, $n = 0, $prefix = "") {
if ($n == strlen($str)) {
echo "$prefix\n";
return;
}
permutations($str, $n + 1, $prefix . $str[$n]);
permutations($str, $n + 1, $prefix . '&#' . ord($str[$n]) . ';');
}
permutations("abcd");
?>

Categories