PHP For Loop strange issue - php

Any reason why this code sometimes only generates 4 character strings?
function genID()
{
$id = '';
$values = '0123456789abcdefghijklmnopqrstuvwxyz';
for($i=0; $i < 5; $i++) :
$str = substr($values, rand(0, strlen($values)), 1);
if(!is_nan(acos($str)))
(mt_rand(0, 1)) ? $str = strtoupper($str) : '';
$id .= $str;
endfor;
return $id; // e.g: ifR8j
}

acos($str) accepts numbers not string.... if u remove the aphabets from the string
ie.
$values = '0123456789abcdefghijklmnopqrstuvwxyz';
to
$values = '0123456789';
you will get the length as 5... Hope this helps..

Try, something simple:
function genID() {
$id = '';
$i = $length = 4;
$possible = "0123456789bcdfghjkmnpqrstvwxyz";
$possibleChar = strlen($possible) - 1;
while ($i) {
$char = $possible[mt_rand(0, $possibleChar)];
while (!strstr($id, $char)) {
$id .= $char;
$i--;
}
}
return $id;
}

(mt_rand(0, 1)) ? $str = strtoupper($str) : '';
This condition is met so sometimes you get an empty char.
Fix the condition or do the loop in some other manner.
For example
while(strlen($id)<5) {
//do the loop
}

The loop iterates 5 times.
rand will also return strlen, so $str will sometimes be ""

$str = substr($values, rand(0, strlen($values))-1, 1);
This will generate 5 characters always.

Related

php get string length and replace first and last 3 characters WITHOUT using a function

I am trying to get the length of a string and replace its first and last 3 characters with a star sign (*) and get the string length WITHOUT using any PHP build in functions.
strlen - substr - preg_replace
Example: $string = "123456789"; $new_string = "***456***";
Is it possible?
I have checked many tutorials and couldn't figure it out. Please help. Thanks!
Universal solution:
$string = "123456789";
$i = 0;
$limit = 3;
while (isset($string[$i])) {
if ($i < $limit) {
$string[$i] = '*';
}
$i++;
}
// you can rewrite this as loop
$string[$i - 1] = '*';
$string[$i - 2] = '*';
$string[$i - 3] = '*';
Starting with php7.1 where negative string indexes are allowed:
$string = "123456789";
// you can rewrite it to a loop too
$string[0] = $string[1] = $string[2] = $string[-1] = $string[-2] = $string[-3] = '*';
echo $string;
Solution without any function, but it emits PHP Notice, you can supress it with #:
$string = "123456789";
$i = 0;
$limit = 3;
while (true) {
if ($string[$i] == '') {
break;
}
if ($i < $limit) {
$string[$i] = '*';
}
$i++;
}
/* Simplified version:
while ($string[$i] != '') {
if ($i < $limit) {
$string[$i] = '*';
}
$i++;
}
*/
$string[$i - 1] = '*';
$string[$i - 2] = '*';
$string[$i - 3] = '*';
echo $string;
I don't know why you don't want to use any PHP functions. However, it is still possible.
<?php
function privacy($string)
{
//get the string length
$i = 0;
/*
while (isset($string[$i])) {
$i++;
}
*/
while ($string[$i] !== "") {
$i++;
}
//replace the first and last 3 characters of the $string with a star
//if the length is bigger than or equals to 6
if ($i >= 6) {
for ($x = 0; $x < 3; $x++) {
$string[$x] = "*";
$string[$i - $x] = "*";
}
}
return $i . "<br>" . $string;
}
echo privacy("123456789");
?>
Will echo out this
9
***456***
I think it is the easiest way to get the string length and replace the first and last 3 characters without confusion. So far!
Good luck!
You can simply achieve it usong loop.(No built-in function)
$string = "123456789";
$i = 0;
$new_str = "";
while(true)
{
$val = #$string[$i];
if($val == "")
break;
if($i<3)
$new_str .= "*";
else
$new_str .= $val;
$i++;
}
for($j=0;$j<$i;$j++)
{
if($j >= ($i-3))
$new_str[$j]="*";
}
echo $new_str;
DEMO
you can access a string like you would access an array.
$var = "leroy jenkins";
$var[2] = 'd';
var_dump($var); // "ledoy jenkins"
but I'm currently not sure how to get the last 3 without using a build in function

String reverse in another way

I'm searching for a function which can reverse a string in another way.
it should always takes the last and the first char of the string.
In example the string
123456
should become
615243
Is there any php function?
EDIT
This is my code so far
$mystring = "1234";
$start = 0;
$end = strlen($mystring);
$direction = 1;
$new_str = '';
while ($start === $end) {
if ($direction == 0) {
$new_str .= substr($mystring, $start, 1);
$start++;
$direction = 1;
} else {
$new_str .= substr($mystring, $end, -1);
$end--;
$direction = 0;
}
}
I couldn't help myself, I just had to write your code for you...
This just takes your string, splits it into an array, then builds up your output string taking letters from the front and end.
$output = '';
$input = str_split('123456');
$length = count($input);
while(strlen($output) < $length) {
$currLength = strlen($output);
if($currLength % 2 === 1) {
$output .= array_shift($input);
}
else {
$output .= array_pop($input);
}
}
echo $output;
Example: http://ideone.com/Xyd0z6
Not very different from Scopey's answer with a for loop:
$str = '123456';
$result = '';
$arr = str_split($str);
for ($i=0; $arr; $i++) {
$result .= $i % 2 ? array_shift($arr) : array_pop($arr);
}
echo $result;
This should work for you:
<?php
$str = "123456";
$rev = "";
$first = substr($str, 0, strlen($str)/2);
$last = strrev(substr($str, strlen($str)/2));
$max = strlen($first) > strlen($last) ? strlen($first): strlen($last);
for($count = 0; $count < $max; $count++)
$rev .= (isset($last[$count])?$last[$count]:"" ) . (isset($first[$count])?$first[$count]: "");
echo $rev;
?>
Output:
615243

Return every other character from string in PHP

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

cut particular pointed string using php

How I cut the extra 0 string from those sample.
current string: 0102000306
required string: 12036
Here a 0 value have in front of each number. So, i need to cut the extra all zero[0] value from the string and get my expected string. It’s cannot possible using str_replace. Because then all the zero will be replaced. So, how do I do it?
Using a regex:
$result = preg_replace('#0(.)#', '\\1', '0102000306');
Result:
"12036"
Using array_reduce:
$string = array_reduce(str_split('0102000306', 2), function($v, $w) { return $v.$w[1]; });
Or array_map+implode:
implode('',array_map('intval',str_split('0102000306',2)));
$currentString = '0102000306';
$length = strlen($currentString);
$newString = '';
for ($i = 0; $i < $length; $i++) {
if (($i % 2) == 1) {
$newString .= $currentString{$i};
}
}
or
$currentString = '0102000306';
$tempArray = str_split($currentString,2);
$newString = '';
foreach($tempArray as $val) {
$newString .= substr($val,-1);
}
It's not particularly elegant but this should do what you want:
$old = '0102000306';
$new = '';
for ($i = 0; $i < strlen($old); $i += 2) {
$new .= $old[$i+1];
}
echo $new;

How to remove characters from a string?

(my first post was not clear and confusing so I've edited the question)
I was studying string manipulation.
You can use strlen() or substr() but cannot rely on other functions that are predefined in libraries.
Given string $string = "This is a pen", remove "is" so that
return value is "Th a pen" (including 3 whitespaces).
Remove 'is' means if a string is "Tsih", we don't remove it. Only "is" is removed.
I've tried (shown below) but returned value is not correct. I've run test test and
I'm still capturing the delimiter.
Thanks in advance!
function remove_delimiter_from_string(&$string, $del) {
for($i=0; $i<strlen($string); $i++) {
for($j=0; $j<strlen($del); $j++) {
if($string[$i] == $del[$j]) {
$string[$i] = $string[$i+$j]; //this grabs delimiter :(
}
}
}
echo $string . "\n";
}
Clarifying, the original quiestion is not Implement a str_replace, It's remove 'is' from 'this is a pen' without any functions and no extra white spaces between words. The easiest way would be $string[2] = $string[3] = $string[5] = $string[6] = '' but that would leave an extra white space between Th and a (Th[ ][ ]a).
There you go, no functions at all
$string = 'This is a pen';
$word = 'is';
$i = $z = 0;
while($string[$i] != null) $i++;
while($word[$z] != null) $z++;
for($x = 0; $x < $i; $x++)
for($y = 0; $y < $z; $y++)
if($string[$x] === $word[$y])
$string[$x] = '';
If you were allowed to use substr() it'd be so much easier. Then you could just loop it and check for the matched value, why can't you use substr() but you can strlen() ?
But without, this works at least:
echo remove_delimiter_from_string("This is a pen","is");
function remove_delimiter_from_string($input, $del) {
$result = "";
for($i=0; $i<strlen($input); $i++) {
$temp = "";
if($i < (strlen($input)-strlen($del))) {
for($j=0; $j<strlen($del); $j++) {
$temp .= $input[$i+$j];
}
}
if($temp == $del) {
$i += strlen($del) - 1;
} else {
$result .= $input[$i];
}
}
return $result;
}
The following code can also used to replace the sub string:
$restring = replace_delimiter_from_string("This is a pen","is", "");
var_dump($restring);
$restring = replace_delimiter_from_string($restring," ", " ");
var_dump($restring);
function replace_delimiter_from_string($input, $old, $new) {
$input_len = strlen($input);
$old_len = strlen($old);
$check_len = $input_len-$old_len;
$result = "";
for($i=0; $i<=$check_len;) {
$sub_str = substr($input, $i, $old_len);
if($sub_str === $old) {
$i += $old_len;
$result .= $new;
}
else {
$result .= $input[$i];
if($i==$check_len) {
$result = $result . substr($input, $i+1);
}
$i++;
}
}
return $result;
}

Categories