Split string into 2 letters - php

I am trying to split a string into 1, 2 and 3 segments.
For example, i currently have this:
$str = 'test';
$arr1 = str_split($str);
foreach($arr1 as $ar1) {
echo strtolower($ar1).' ';
}
Which works well on 1 character splitting, I get:
t e s t
However when I try:
$arr2 = str_split($str, 2);
I get:
te st
Is there a way so that I can output this? :
te es st
and then also with 3 characters like this?
tes est

Here it is:
function SplitStringInWeirdWay($string, $num) {
for ($i = 0; $i < strlen($string)-$num+1; $i++) {
$result[] = substr($string, $i, $num);
}
return $result;
}
$string = "aeioubcdfghjkl";
$array = SplitStringInWeirdWay($string, 4);
echo "<pre>";
print_r($array);
echo "</pre>";
PHPFiddle Link: http://phpfiddle.org/main/code/1bvp-pyk9
And after that, you can just simply echo it in one line, like:
echo implode($array, ' ');

Try this, change $length to 1 or 3:
$string = 'test';
$length = 2;
$start = -1;
while( $start++ + $length < strlen( $string ) ) {
$array[] = substr( $string, $start, $length );
}
print_r( $array );
/*
Array
(
[0] => te
[1] => es
[2] => st
)
*/

Use
$string{0} $string{1} $string{n}
to get the characters you want !
Then you can use a loop on your string using strlen
$length = strlen($string);
for($i = 0; $i < $length; ++$i){
// Your job
}
Then use $i, $i - 1, $i + 1 to pick the characters.

<?php
function my_split($string, $count){
if(strlen($string) <= $count){
return $string;
}
$my_string = "";
for($i; $i< strlen($string) - $count + 1; $i++){
$my_string .= substr($string, $i, $count). ' ';
}
return trim($my_string);
}
echo my_split('test', 3);
?>
And will have "tes est"

Simplest way, you can do it with chunk_split:
$str = "testgapstring";
$res = chunk_split($str, 3, ' ');
echo $res; // 'tes tga pst rin g '
but you have extra space symbol at the end, also if you need this to be an array something will work:
$chunked = chunk_split($str, 3, ' ');
$arr = explode(' ', rtrim($chunked));
Other example:
echo $chunked = rtrim(chunk_split('test', 2, ' ')); // 'te st'

function luhn_Approved($;500) {
$str = '';4815821101619134=2408101
foreach( array_reverse( str_split( $num ) ) as $i => $c ) $str .= ($i % 2 ? $c * 2 : $c );
return array_sum( str_split($str) ) % 10 == 0;
}
function SplitStringInWeirdWay($string, $0) {
for ($i = 0; $i < strlen($string)-$num+1; $i++) {
$result[] = substr($string, $i, $num);
}
return $result;
}
$string = "aeioubcdfghjkl";
$array = SplitStringInWeirdWay($string, 4);
echo "<pre>"; print_r($array); echo "</pre>";

Related

How to echo data array

I'm new for this, can anyone solve my problem?
this is my code :
<?php
$data = array("Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday");
$datastart = 3;
$string = join(',', $data);
echo $string;
?>
This echo will be result :
Sunday,Monday,Tuesday,Wednesday,Thursday,Friday,Saturday
I want a result like this:
Wednesday,Thursday,Friday,Saturday,Sunday,Monday,Tuesday
thank you for the answer :)
You can use array_slice to extract the portions of your array in the order you want to output them, and then array_merge to put them back together:
$data = array("Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday");
$datastart = 3;
$string = implode(',', array_merge(array_slice($data, $datastart), array_slice($data, 0, $datastart)));
echo $string;
Or you can use a simple for loop:
$len = count($data);
$string = '';
for ($i = 0; $i < $len; $i++) {
$string .= ($i > 0 ? ',' : '') . $data[($i + $datastart) % $len];
}
echo $string;
Output:
Wednesday,Thursday,Friday,Saturday,Sunday,Monday,Tuesday
Demo on 3v4l.org

How to generate a random 6-character string with alternating letters and numbers?

I have a code in PHP that is able to generate a 6-character alpha-numeric string but it does not ensure that there are 3 letters and 3 numbers generated.
It generates a string such as "ps7ycn"
It does not have 3 numbers in between the alphabet.
The numbers should be in between the letters.
example : a3g5h9
This will ensure you only get alternating letters and numbers:
Code: (Demo)
$letters='abcdefghijklmnopqrstuvwxyz'; // selection of a-z
$string=''; // declare empty string
for($x=0; $x<3; ++$x){ // loop three times
$string.=$letters[rand(0,25)].rand(0,9); // concatenate one letter then one number
}
echo $string;
Potential Outputs:
i9f6q0
j4u5p4
j6l6n9
p.s. If you want to randomize whether the first character is a letter or number, use this line of code after the for loop.
if(rand(0,1)){$string=strrev($string);}
rand() will generate a 0 or a 1, the conditional will treat 0 as false and 1 as true. This offers a "coin flip" scenario regarding whether to reverse the string or not.
If you want to guarantee unique letters and numbers in the output...
$letters=range('a','z'); // ['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']
shuffle($letters);
$numbers=range(0,9); // [0,1,2,3,4,5,6,7,8,9]
shuffle($numbers);
$string='';
for($x=0; $x<3; ++$x){
$string.=$letters[$x].$numbers[$x];
}
echo $string;
Try this code:
$str = '';
for ( $i = 1; $i <= 6; ++$i ) {
if ( $i % 2 ) {
$str .= chr(rand(97,122));
}else{
$str .= rand(0,9);
}
}
This one is shorter but you can not use it to have odd length like a1g7y5k :
$str = '';
for ( $i = 1; $i <= 3; ++$i ) {
$str .= chr(rand(97,122)) . rand(0,9);
}
-Alternatively use this method that can be improved ( refer to mickmackusa's comments):
$alphas = 'abcdefghijklmnopqrstuvwxyz';
$numbers = '0123456789';
$arr1 = str_split($alphas);
$arr2 = str_split($numbers);
$arr3 = array_rand($arr1,3);
$arr4 = array_rand($arr2,3);
$arr5 = array();
for ($i=0; $i<count($arr3); $i++) {
$arr5[] = $arr3[$i];
$arr5[] = $arr4[$i];
}
$result = implode('',$arr5);
Check this thread.It has some good ideas and functions.
Here's one way you could address this:
$alpha = 'abcdefghijklmnopqrstuvwxyz';
$number = '0123456789';
$random = '';
for ( $i = 0; $i < 6; ++$i ) {
if ( $i % 2 ) {
$random .= substr( $number, rand( 0, strlen( $number ) - 1 ), 1 );
} else {
$random .= substr( $alpha, rand( 0, strlen( $alpha ) - 1 ), 1 );
}
}
$random will now contain a six-character random value with the first, third, and fifth characters coming from $alpha and second, fourth, and sixth characters coming from $number.
You can use this function
<?php
public static function random_string($charsNo = 3, $NumbersNo = 3)
{
$character_set_array = array();
$character_set_array[] = array('count' => $charsNo, 'characters' => 'abcdefghijklmnopqrstuvwxyzasdsawwfdgrzvyuyiuhjhjoppoi');
$character_set_array[] = array('count' => $NumbersNo, 'characters' => '0123456789');
$temp_array = array();
foreach ($character_set_array as $character_set) {
for ($i = 0; $i < $character_set['count']; $i++) {
$temp_array[] = $character_set['characters'][rand(0, strlen($character_set['characters']) - 1)];
}
}
shuffle($temp_array);
return implode('', $temp_array);
}
?>

Find the 3 longest words from string

What I need to add to this script to get 3 longest words from string?
<?php
$text = 'one four eleven no upstairs';
$arr = explode(" ", $text);
$max = $arr[0];
for ($i = 0; $i < count($arr); $i++) {
if (strlen($arr[$i]) > strlen($max)) {
$max = $arr[$i];
}
}
echo $max;
?>
Please help to modify the script. We have to not use the usort function.
The solution would be like this:
Use explode() to get the words of the string in an array
"Partially" sort the array elements in descending order of length
Use a simple for loop to print the longest three words from the array.
So your code should be like this:
$text = 'one four eleven no upstairs';
$arr = explode(" ", $text);
$count = count($arr);
for($i=0; $i < $count; $i++){
$max = $arr[$i];
$index = $i;
for($j = $i + 1; $j < $count; ++$j){
if(strlen($arr[$j]) > strlen($max)){
$max = $arr[$j];
$index = $j;
}
}
$tmp = $arr[$index];
$arr[$index] = $arr[$i];
$arr[$i] = $tmp;
if($i == 3) break;
}
// print the longest three words
for($i=0; $i < 3; $i++){
echo $arr[$i] . '<br />';
}
Alternative method: (Using predefined functions)
$text = 'one four eleven no upstairs';
$arr = explode(" ", $text);
usort($arr,function($a, $b){
return strlen($b)-strlen($a);
});
$longest_string_array = array_slice($arr, 0, 3);
// display $longest_string_array
var_dump($longest_string_array);
You need to create your own comparative function and pass it with array to usort php function.
Ex.:
<?php
function lengthBaseSort($first, $second) {
return strlen($first) > strlen($second) ? -1 : 1;
}
$text = 'one four eleven no upstairs';
$arr = explode(" ", $text);
usort($arr, 'lengthBaseSort');
var_dump(array_slice($arr, 0, 3));
It will output 3 longest words from your statement.
According to author changes:
If you have no ability to use usort for some reasons (may be for school more useful a recursive function) use following code:
<?php
$text = 'one four eleven no upstairs';
$arr = explode(" ", $text);
function findLongest($inputArray) {
$currentIndex = 0;
$currentMax = $inputArray[$currentIndex];
foreach ($inputArray as $key => $value) {
if(strlen($value) > strlen($currentMax)){
$currentMax = $value;
$currentIndex = $key;
}
}
return [$currentIndex, $currentMax];
}
for($i = 0; $i < 3; $i++) {
$result = findLongest($arr);
unset($arr[$result[0]]);
var_dump($result[1]);
}
?>

I have a program of spilting words but i don't want it in array

Hey i have a php program which is to spilt the words. I wanted it not to come in array. Instead of array i wanted it in div or span. Please help me to solve these problem. Thanks in advance.
Here is my php code
<?php
function str_split_len($str, $len)
{
if( $len > strlen($str) )
{
return false;
}
$strlen = strlen($str);
$result = array();
$words = ($strlen / $len);
for( $x = 1; $x <= $len; $x++ )
{
$result[] = substr($str, 0, $words);
$str = substr($str, $words, $strlen);
}
return $result;
}
/* Example */
$res = str_split_len("Split me !haha!", 3);
print_r($res);
?>
you can use implode function to join array:
$res = str_split_len("Split me !haha!", 3);
echo '<span>'.implode('</span><span>', $res).'</span>';
Just use a string instead of an array and concatenate the parts with <div> or <span>:
<?php
function str_split_len($str, $len)
{
if( $len > strlen($str) )
{
return false;
}
$strlen = strlen($str);
$result = '';
$words = ($strlen / $len);
for( $x = 1; $x <= $len; $x++ )
{
$result .= '<div>'.substr($str, 0, $words).'</div>';
$str = substr($str, $words, $strlen);
}
return $result;
}
/* Example */
$res = str_split_len("Split me !haha!", 3);
echo $res;
?>
And you will get
<div>Split</div><div> me !</div><div>haha!</div>

Rotate a string N times in PHP

I'm looking for a way to rotate a string to the left N times. Here are some examples:
Let the string be abcdef
if I rotate it 1 time I want
bcdefa
if I rotate it 2 time I want
cdefab
if I rotate it 3 time I want
defabc
.
.
If I rotate the string its string
length times, I should get back the
original string.
$rotated = substr($str, $n) . substr($str, 0, $n);
Here is one variant that allows arbitrary shifting to the left and right, regardless of the length of the input string:
function str_shift($str, $len) {
$len = $len % strlen($str);
return substr($str, $len) . substr($str, 0, $len);
}
echo str_shift('abcdef', -2); // efabcd
echo str_shift('abcdef', 2); // cdefab
echo str_shift('abcdef', 11); // fabcde
function rotate_string ($str, $n)
{
while ($n > 0)
{
$str = substr($str, 1) . substr($str, 0, 1);
$n--;
}
return $str;
}
There is no standard function for this but is easily implemented.
function rotate_left($s) {
return substr($s, 1) . $s[0];
}
function rotate_right($s) {
return substr($s, -1) . substr($s, 0, -1);
}
You could extend this to add an optional parameter for the number of characters to rotate.
function rotate_string($str) {
for ($i=1; $i<strlen($str)+1;$i++) {
#$string .= substr($str , strlen($str)-$i , 1);
}
return $string;
}
echo rotate_string("string"); //gnirts
Use this code
<?php
$str = "helloworld" ;
$res = string_function($str,3) ;
print_r ( $res) ;
function string_function ( $str , $count )
{
$arr = str_split ( $str );
for ( $i=0; $i<$count ; $i++ )
{
$element = array_pop ( $arr ) ;
array_unshift ( $arr, $element ) ;
}
$result=( implode ( "",$arr )) ;
return $result;
}
?>
You can also get N rotated strings like this.
$str = "Vijaysinh";
$arr1 = str_split($str);
$rotated = array();
$i=0;
foreach($arr1 as $a){
$t = $arr1[$i];
unset($arr1[$i]);
$rotated[] = $t.implode($arr1);
$arr1[$i] = $t;
$i++;
}
echo "<pre>";print_r($rotated);exit;

Categories