php remove n chars from nth index of a string - php

This question relates to an existing topic here..
Remove first 4 characters of a string with PHP
but instead what if i would like to remove specific number of characters from a specific index of a string?
e.g
(i want to remove 8 characters from the fourth index)
$input = 'asdqwe123jklzxc';
$output = 'asdlzxc';

I think you need this:
echo substr_replace($input, '', 3, 8);
More information here:
http://www.php.net/manual/de/function.substr-replace.php

$input = 'asdqwe123jklzxc';
echo str_replace(substr($input, 3, 8), '', $input);
Demo

You can try with:
$output = substr($input, 0, 3) . substr($input, 11);
Where 0,3 in first substr are 4 letters in the beggining and 11 in second is 3+8.
For better expirience you can wrap it with function:
function removePart($input, $start, $length) {
return substr($input, 0, $start - 1) . substr($input, $start - 1 + $length);
}
$output = removePart($input, 4, 8);

I think you can try :
function substr_remove(&$input, $start, $length) {
$subpart = substr($input, $start, $length);
$input = substr_replace($input, '', $start, $length);
return $subpart;
}

Related

How to add value substring inside decimal in PHP

I have a number like this
"0.321527778"
I want make some substring from my value in top and then for the substring result I want input that number into the my decimal number, how can I do? (for substring I cut from 2 last digits from decimal number)
for the expetation result will be like this :
"0.321527777777778"
code :
<?php
$number = "0.321527778";
$substring = substr($number, -2, -1);
print_r($number . ' ' . $substring);
?>
result :
0.321527778 7
If my explanation is incomprehensible, I apologize, and you can ask me again, Thank You
You need to get the substrings before and after the part that you want to insert multiple times. Then concatenate everything without putting spaces between them.
$number = "0.321527778";
$beginning = substr($number, 0, -2);
$end = substr($number, -1);
$substring = substr($number, -2, -1);
$result = $beginning . str_repeat($substring, 6) . $end;
echo $result;

How to split a string into chunks of non-fixed lengths using php?

End goal: Changing chunks of numbers in a database like 0000000 and 22222 and 333333333333 into different lengths. For example, phone numbers that may include prefixes like country codes (e.g. +00 (000) 000-0000, or a pattern of 2, 3, 3, 4), so the option of being able to change the length depending on a different phone number format would be nice.
I love the idea of using explode or chunk_split for the simplicity, as I will be processing a lot of data and I don't want it to drain the server too much:
$string = "1111111111";
$new_nums = chunk_split($string, 3, " ");
echo $new_nums;
^ Only problem here is that I can only use one digit for the length.
What's the best way to go about it? Should I create a function?
Although you mention a phone number in your example it sounds like you wanted something that could do more while also being allowed to specify multiple and variable chunk lengths. One way to do this is to create a function that takes your data, delimiter/separator character and a number of chunk values.
You could make use of func_num_args() and func_get_args() to figure out your chunk lengths.
Here is an example of such a function:
<?php
function chunkData($data, $separator)
{
$rebuilt = "";
$num = func_num_args();
$args = func_get_args();
if($num > 2)
{
for($i = 2; $i < $num; $i++)
{
if(strlen($data) > 0)
{
$string = substr($data, 0, $args[$i]);
$segment = strpos($data, $string);
if($segment !== false)
{
$rebuilt .= $string . $separator;
$data = substr_replace($data, "", 0, $args[$i]);
}
}
}
}
$rebuilt .= $data;
$rebuilt = rtrim($rebuilt, $separator);
return $rebuilt;
}
//Usage examples:
printf("Phone number: %s \n", chunkData("2835552093", "-", 3, 3, 4));
printf("Groups of three letters: %s \n", chunkData("ABCDEFGHI", " ", 3, 3, 3));
printf("King Roland's passcode: %s \n", chunkData("12345", ",", 1, 1, 1, 1, 1));
printf("Append leftovers: %s \n", chunkData("BlahBlahBlahJustPlainBlah", " ", 4, 4, 4));
printf("Doesn't do much: %s \n", chunkData("huh?", "-"));
?>
//Output:
Phone number: 283-555-2093
Groups of three letters: ABC DEF GHI
King Roland's passcode: 1,2,3,4,5
Append leftovers: Blah Blah Blah JustPlainBlah
Doesn't do much: huh?
With regex?
$regex = "/(\\d{2})(\\d{3})(\\d{3})(\\d{4})/";
$number = "111111111111";
$replacement = "+$1 ($2) $3-$4";
$result = preg_replace($regex, $replacement, $number);
https://regex101.com/r/gS1uC1/1

Adding a string and an integer in php

I'm trying to add a 1 in front of my binary code and this is how I'm going about it:
if I have 0101, for example, then I'd add a number with 4 zeroes, like 10000 so it would become 10101. Here's my code:
$fill = strlen($string);
$number = '1';
$add = str_pad($number, $fill, '0', STR_PAD_RIGHT);
$m1 = $string + $add;
The problem is the output for that is something like 1.random number e+Random number
assuming $string is your "0101" string, you could just do $m1 = '1'.$string;
My previous answer was wrong because the length of the string is potentially variable and str_pad requires you to know the length. This will work, but it doesn't look so elegant:
if (strpos($string, '0') === 0) {
$string = '1' . $string;
}

Add space after every 4th character

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

How to extract substring by start-index and end-index?

$str = 'HelloWorld';
$sub = substr($str, 3, 5);
echo $sub; // prints "loWor"
I know that substr() takes the first parameter, 2nd parameter is start index, while 3rd parameter is substring length to extract. What I need is to extract substring by startIndex and endIndex. What I need is something like this:
$str = 'HelloWorld';
$sub = my_substr_function($str, 3, 5);
echo $sub; // prints "lo"
Is there a function that does that in php? Or can you help me with a workaround solution, please?
It's just math
$sub = substr($str, 3, 5 - 3);
The length is the end minus the start.
function my_substr_function($str, $start, $end)
{
return substr($str, $start, $end - $start);
}
If you need to have it multibyte safe (i.e. for chinese characters, ...) use the mb_substr function:
function my_substr_function($str, $start, $end)
{
return mb_substr($str, $start, $end - $start);
}
Just subtract the start index from the end index and you have the length the function wants.
$start_index = 3;
$end_index = 5;
$sub = substr($str, $start_index, $end_index - $start_index);
You can just use a negative value on the third parameter:
echo substr('HelloWorld', 3, -5);
// will print "lo"
If length is given and is negative, then that many characters will be omitted from the end of string (after the start position has been calculated when a start is negative).
As stated at the substr documentation.
Not exactly...
If we have a start index as 0, and we want JUST the first char, it becomes difficult as this will not output what you want. So if your code is requiring an $end_index:
// We want just the first char only.
$start_index = 0;
$end_index = 0;
echo $str[$end_index - $start_index]; // One way... or...
if($end_index == 0) ++$end_index;
$sub = substr($str, $start_index, $end_index - $start_index);
echo $sub; // The other way.

Categories