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

$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.

Related

php remove n chars from nth index of a string

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;
}

Finding a character at a specific position of a string

Since I am still new to PHP, I am looking for a way to find out how to get a specific character from a string.
Example:
$word = "master";
$length = strlen($word);
$random = rand(1,$length);
So let's say the $random value is 3, then I would like to find out what character the third one is, so in this case the character "s". If $random was 2 I would like to know that it's a "a".
I am sure this is really easy, but I tried some substr ideas for nearly an hour now and it always fails.
Your help would be greatly appreciated.
You can use substr() to grab a portion of a string starting from a point and going length. so example would be:
substr('abcde', 1, 1); //returns b
In your case:
$word = "master";
$length = strlen($word) - 1;
$random = rand(0,$length);
echo substr($word, $random, 1);//echos single char at random pos
See it in action here
You can use your string the same like 0-based index array:
$some_string = "apple";
echo $some_string[2];
It'll print 'p'.
or, in your case:
$word = "master";
$length = strlen($word);
$random = rand(0,$length-1);
echo $word[$random];
Try this simply:
$word = "master";
$length = strlen($word);
$random = rand(0,$length-1);
if($word[$random] == 's'){
echo $word[$random];
}
Here I used 0 because $word[0] is m so that we need to subtract one from strlen($word) for getting last character r
Use substr
$GetThis = substr($myStr, 5, 5);
Just use the same values for the same or different if you want multiple characters
$word = "master";
$length = strlen($word);
$random = rand(0,$length-1);
$GetThis = substr($word, $random, $random);
As noted in my comment (I overlooked as well) be sure to start your rand at 0 to include the beginning of your string since the m is at place 0. If we all overlooked that it wouldn't be random (as random?) now would it :)
You can simply use $myStr{$random} to obtain the nth character of the string.

keep preceeding zeros when working with a integer

I'm using this code:
$start = substr($string, 0, -6);
$end = substr($string, -6);
for($i = 0; $i < 500; $i++) {
if($end > 500) {
echo $start.$end--."<br />";
} else {
echo $start.$end++."<br />";
}
}
Where $string will something like RXV123456 always last 6 characters will be a number.
If $string is RXV123456, the output will be someting like:
RXV123456
RXV123455
RXV123454
...
But, if $string will be something like RXV012345, I get this output:
RXV12345
RXV12344
RXV12343
Also if $string will be RXV001234 or RXV000123, same thing, that zeros will be omitted.
Any ideas how to keep the zeros if $end will start with one ore more zeros?
Any programming language will truncate zeros on the left side of an integer. If you want them to display, you can use a function like str_pad to add them when concatenating with the other string.

Increment through A-Za-z0-9 in expanding string with PHP

I'm trying to generate strings in PHP with a group of valid characters, cycling through them and appending an extra character on the end of the string, until maximum length is reached. For example, desired output:
a,b,c,d,e,f,aa,ab,ac,ad,ae,af,ba,bb,bc,bd,be,bf,ca,cb..etc
This is my PHP function so far:
<?php
$chars = Array('a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z',
'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','X','Y','Z',
'1','2','3','4','5','6','7','8','9','0');
$maxlen = 10;
$input = $chars[0];
while (1):
echo buildInput($maxlen, $chars, $input) . "\n";
endwhile;
function buildInput($maxlen, $chars, $previous)
{
if (array_search(substr($previous, -1), $chars) == sizeof($chars) - 1):
// end of input cycle reached, add another character
$previous = $previous . $chars[0];
endif;
if (strlen($previous) > $maxlen):
die('Max length reached');
endif;
// Remove last character, and append incremented char
$input = substr($previous, 0, -1);
$input = $input . $chars[array_search(substr($previous, -1), $chars)+1];
return $input;
}
?>
It only increments the last character of the string which gets to 0, then appends 'a' and starts over but without trying all the other possible permutations.
Could someone help me with a better method?
Is this the kind of thing you want?
<?php
$chars = array('a','b','c');
$max_length = 3;
function build($base_arr, $ctr) {
global $chars;
global $max_length;
$combos = array();
foreach ($base_arr as $base) {
foreach ($chars as $char) {
echo $base, $char, '<br />';
$combos[] = $base.$char;
}
}
if ($ctr < $max_length) {
build($combos, $ctr + 1);
}
}
foreach ($chars as $char) {
echo $char, '<br />';
}
build($chars, 2);
?>
It'll give you: a, b, c, aa, ab, ac, ba, bb, bc, ca, cb, cc, ..., bcc, caa, cab, cac, cba, cbb, cbc, cca, ccb, ccc.
Your array is so large, though, that using this method on it would take up way too much memory to work. Out of 62 characters (A-Z, a-z, 0-9), the number of possible 10-character permutations is 8.4 x 10^17; so hopefully, you'll be able to find a more efficient method or figure out a way to get the result you want without having to cycle through such a large array. I hope you find what you're looking for!
If you limit yourself to 0-9,a-z (only lower case), then you could use base_convert for this and do it in one line:
for($i = 0; $i < 1000; $i++) echo base_convert($i, 10, 36) . '<br/>';
Here's a demo.
This will print 200 letters: a,b,c,d,...,aa,...,cq
The buildString function will build our string from the least significant number (right) to the most significant (left). By performing a modulus division, you will find the array position of the next character. Add this character to the front of your string, and divide
your number by the size of your array (which is the base number in your character based number system), ignoring the rest.
To explain the method using our normal 10-based number system and the input of 123, you would simply pick the last digit, 3, divide the input by 10, pick the last digit 2, divide the input by 10, pick the last digit 1, divide the input by 10. The input is now 0 and your output is ready...
$chars = array('a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q'
,'r','s','t','u','v','w','x','y','z','A','B','C','D','E','F','G','H','I','J'
,'K','L','M','N','O','P','Q','R','S','T','U','V','X','Y','Z','1','2','3','4'
,'5','6','7','8','9','0');
$numChars = count($chars);
// Output numbers from 1 to 200 (a to cq)
for($i = 1; $i <= 200; $i++) {
echo buildString($i).'<br>';
}
// Will also work fine for large numbers - output "dxSA"
echo buildString(1000000).'<br>';
function buildString($int) {
global $chars;
global $numChars;
$output = '';
while($int) {
$output = $chars[($int-1) % $numChars] . $output;
$int = floor(($int-1) / $numChars);
}
return $output;
}
If you have access to gmp extension and PHP 5.3.2+ this will work for the charset you specified:
$result = strtr(
gmp_strval(gmp_init($i, 10), 62),
'0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz',
'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'
);

How can i extract the portion of a string giving the beginning and the end position?

How can i extract the portion of a string giving the beginning and the end position?
I know there is a method called substr() but is not what im looking for (the third parameter is lenght of the portion..)
If you have the start and end positions, the length is just end - start:
$string = "The quick brown fox jumped over the lazy dog";
$start = 4;
$end = 15;
substr($string, $start, $end - $start); //=> "quick brown"
See this in action at http://www.ideone.com/LRfYT.
If you know the beginning and end locations, all you have to do is subtract to get the length of the part you want. Then go ahead and use substr().
Th following will do what you want.
function ssubstr($string, $start, $end) {
if ($end < 0) $length = strlen($string) + $end;
else $length = $end - $start;
return substr($string, $start, $length);
}
This method is safe for negative values of $end.
Note that it doesn't do any error checking

Categories