Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
I want to reverse two characters of string in PHP. For example 50378f to 8f3750 please help me.
$str= User::where('id',$userid)->pluck('card_id');
$num = strrev($number);
echo $num;
This function is reversing very good but I want to reverse two characters not one character.
My function is giving me output example: 12345 to 543210 but I want it like
103254.
You can try this:
$originalString = '23242526';
$arrayWith2CharsPerElement = str_split($originalString, 2);
$arrayWithReversedKeys = array_reverse($arrayWith2CharsPerElement);
$newStringInReverseOrder = implode($arrayWithReversedKeys);
echo $newStringInReverseOrder; //will print 26252423
Edit: changed the approach to work with odd strings
$string = '121314152';
$countDown = strlen($string);
$substrLength = 2;
$reverseString = '';
while ($countDown > 0) {
$startPosition = $countDown -2;
if ($countDown == 1) {
$startPosition = 0;
$substrLength = 1;
}
$reverseString .= substr($string, $startPosition, $substrLength);
$countDown -= 2;
}
echo $reverseString; //will print 524131211
You can try
function strReverse($string) {
$newString = "";
if ((strlen($string) % 2) != 0) $string = "0". $string;
for($pos = 0; $pos < strlen($string); $pos++) {
$chr = substr($string, $pos, 1);
if (($pos % 2) == 0) {
$tmp = $chr;
} else {
$newString .= $chr . $tmp;
$tmp = "";
}
}
if ($tmp != "") $newString .= $tmp;
return $newString;
}
echo strReverse('12345'); // result 103254
I have rewrite the function, you can define how many length of character you want to reverse by modify $noOfChar.
Example, if you set $noOfChar = 3, 12345 result will be 1004325.
function strReverse($string) {
$newString = "";
$noOfChar = 2;
$remain = strlen($string) % $noOfChar;
$string = str_repeat("0", $remain) . $string;
$segment = "";
for($pos = 0; $pos < strlen($string); $pos++) {
$segment = $segment . substr($string, $pos, 1);
if ((($pos + 1) % $noOfChar) == 0) {
$newString .= strrev($segment);
$segment = "";
}
}
if ($segment != "") $newString .= strrev($segment);
return $newString;
}
echo strReverse('12345');
You can use below function for reverse string by two slot.
function reverseByTwoCharacters($string)
{
$stringReversed = "";
if (!empty($string)) {
$stringLength = strlen($string);
if ($stringLength % 2 == 0) {
$splittedString = str_split($string, 2);
} else {
$splittedString = str_split(substr($string, 1), 2);
array_unshift($splittedString, $string[0]);
}
$reverseString = array_reverse($splittedString);
$stringReversed = implode($reverseString);
}
return $stringReversed;
}
$string = "1234567890";
echo reverseByTwoCharacters($string);
// Output
9078563412
Related
I have a string like $str.
$str = "00016cam 321254300022cam 321254312315300020cam 32125433153";
I want to split it in array like this. The numbers before 'cam' is the string length.
$splitArray = ["00016cam 3212543", "00022cam 3212543123153", "00020cam 32125433153"]
I have tried following code:
$lengtharray = array();
while ($str != null)
{
$sublength = substr($str, $star, $end);
$star += (int)$sublength; // echo $star."<br>"; // echo $sublength."<br>";
if($star == $total)
{
exit;
}
else
{
}
array_push($lengtharray, $star); // echo
print_r($lengtharray);
}
You can try this 1 line solution
$str = explode('**', preg_replace('/\**cam/', 'cam', $str)) ;
If your string doesn't contain stars then I'm afraid you need to write a simple parser that will:
take characters from the left until it's not numeric
do substr having the length
repeat previous steps on not consumed string
<?php
$input = "00016cam 321254300022cam 321254312315300020cam 32125433153";
function parseArray(string $input)
{
$result = [];
while ($parsed = parseItem($input)) {
$input = $parsed['rest'];
$result[] = $parsed['item'];
}
return $result;
}
function parseItem(string $input)
{
$sLen = strlen($input);
$len = '';
$pos = 0;
while ($pos < $sLen && is_numeric($input[$pos])) {
$len .= $input[$pos];
$pos++;
}
if ((int) $len == 0) {
return null;
}
return [
'rest' => substr($input, $len),
'item' => substr($input, 0, $len)
];
}
var_dump(parseArray($input));
this code works for me. hope helps.
$str = "**00016**cam 3212543**00022**cam 3212543123153**00020**cam 32125433153";
$arr = explode("**", $str);
for ($i=1; $i < sizeof($arr); $i=$i+2)
$arr_final[]=$arr[$i].$arr[$i+1];
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
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
This question already has answers here:
Reverse the letters in each word of a string
(6 answers)
Closed 1 year ago.
This task has already been asked/answered, but I recently had a job interview that imposed some additional challenges to demonstrate my ability to manipulate strings.
Problem: How to reverse words in a string? You can use strpos(), strlen() and substr(), but not other very useful functions such as explode(), strrev(), etc.
Example:
$string = "I am a boy"
Answer:
I ma a yob
Below is my working coding attempt that took me 2 days [sigh], but there must be a more elegant and concise solution.
Intention:
1. get number of words
2. based on word count, grab each word and store into array
3. loop through array and output each word in reverse order
Code:
$str = "I am a boy";
echo reverse_word($str) . "\n";
function reverse_word($input) {
//first find how many words in the string based on whitespace
$num_ws = 0;
$p = 0;
while(strpos($input, " ", $p) !== false) {
$num_ws ++;
$p = strpos($input, ' ', $p) + 1;
}
echo "num ws is $num_ws\n";
//now start grabbing word and store into array
$p = 0;
for($i=0; $i<$num_ws + 1; $i++) {
$ws_index = strpos($input, " ", $p);
//if no more ws, grab the rest
if($ws_index === false) {
$word = substr($input, $p);
}
else {
$length = $ws_index - $p;
$word = substr($input, $p, $length);
}
$result[] = $word;
$p = $ws_index + 1; //move onto first char of next word
}
print_r($result);
//append reversed words
$str = '';
for($i=0; $i<count($result); $i++) {
$str .= reverse($result[$i]) . " ";
}
return $str;
}
function reverse($str) {
$a = 0;
$b = strlen($str)-1;
while($a < $b) {
swap($str, $a, $b);
$a ++;
$b --;
}
return $str;
}
function swap(&$str, $i1, $i2) {
$tmp = $str[$i1];
$str[$i1] = $str[$i2];
$str[$i2] = $tmp;
}
$string = "I am a boy";
$reversed = "";
$tmp = "";
for($i = 0; $i < strlen($string); $i++) {
if($string[$i] == " ") {
$reversed .= $tmp . " ";
$tmp = "";
continue;
}
$tmp = $string[$i] . $tmp;
}
$reversed .= $tmp;
print $reversed . PHP_EOL;
>> I ma a yob
Whoops! Mis-read the question. Here you go (Note that this will split on all non-letter boundaries, not just space. If you want a character not to be split upon, just add it to $wordChars):
function revWords($string) {
//We need to find word boundries
$wordChars = 'abcdefghijklmnopqrstuvwxyz';
$buffer = '';
$return = '';
$len = strlen($string);
$i = 0;
while ($i < $len) {
$chr = $string[$i];
if (($chr & 0xC0) == 0xC0) {
//UTF8 Characer!
if (($chr & 0xF0) == 0xF0) {
//4 Byte Sequence
$chr .= substr($string, $i + 1, 3);
$i += 3;
} elseif (($chr & 0xE0) == 0xE0) {
//3 Byte Sequence
$chr .= substr($string, $i + 1, 2);
$i += 2;
} else {
//2 Byte Sequence
$i++;
$chr .= $string[$i];
}
}
if (stripos($wordChars, $chr) !== false) {
$buffer = $chr . $buffer;
} else {
$return .= $buffer . $chr;
$buffer = '';
}
$i++;
}
return $return . $buffer;
}
Edit: Now it's a single function, and stores the buffer naively in reversed notation.
Edit2: Now handles UTF8 characters (just add "word" characters to the $wordChars string)...
My answer is to count the string length, split the letters into an array and then, loop it backwards. This is also a good way to check if a word is a palindrome. This can only be used for regular string and numbers.
preg_split can be changed to explode() as well.
/**
* Code snippet to reverse a string (LM)
*/
$words = array('one', 'only', 'apple', 'jobs');
foreach ($words as $d) {
$strlen = strlen($d);
$splits = preg_split('//', $d, -1, PREG_SPLIT_NO_EMPTY);
for ($i = $strlen; $i >= 0; $i=$i-1) {
#$reverse .= $splits[$i];
}
echo "Regular: {$d}".PHP_EOL;
echo "Reverse: {$reverse}".PHP_EOL;
echo "-----".PHP_EOL;
unset($reverse);
}
Without using any function.
$string = 'I am a boy';
$newString = '';
$temp = '';
$i = 0;
while(#$string[$i] != '')
{
if($string[$i] == ' ') {
$newString .= $temp . ' ';
$temp = '';
}
else {
$temp = $string[$i] . $temp;
}
$i++;
}
$newString .= $temp . ' ';
echo $newString;
Output: I ma a yob
(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;
}