php splitting large numbers (like explode) - php

i need the functionality of php explode(), but without the separators.
for example, turning the variable "12345" into an array, holding each number seperately.
is this possible? i've already googled but only found explode(), which doesn't seem to work.
thanks!

with any string in php:
$foo="12345";
echo $foo[0];//1
echo $foo[1];//2
//etc
or (from the preg_split()) page in the manual
$str = 'string';
$chars = preg_split('//', $str, -1, PREG_SPLIT_NO_EMPTY);
print_r($chars);
EVEN BETTER:
$str = 'string';
$chars=str_split($str, 1)
print_r($chars);
benchmark of preg_split() vs str_split()
function microtime_float()
{
list($usec, $sec) = explode(" ", microtime());
return ((float)$usec + (float)$sec);
}
$str = '12345';
$time_start = microtime_float();
for ($i = 0; $i <100000; $i++) {
$chars = preg_split('//', $str, -1, PREG_SPLIT_NO_EMPTY);
//$chars=str_split($str, 1);
}
$time_end = microtime_float();
$time = $time_end - $time_start;
echo "$time seconds\n";
results:
str_split =0.69
preg_split =0.9

If you actually want to create an array, then use str_split(), i.e.,
echo '<pre>'. print_r(str_split("123456", 1), true) .'</pre>';
would result in
Array
(
[0] => 1
[1] => 2
[2] => 3
[3] => 4
[4] => 5
)

Your number can be turned into string and then acted like an array
$i = 2342355; $i=(string)$i;
//or
$i='234523452435234523452452452';
//then
$i[2]==4
//numeration started from 0

Related

php change the array value

I have an Array like this
$first = array("10.2+6","5.3+2.2");
I want to convert it like this
$second = array("10+10+6","5+5+5+2+2");
I also want to print out this such as way
10
10
6
5
5
5
2
2
How can I do this?
You can use this preg_replace_callback function:
$first = array("10.2+6", "5.3+2.2");
$second = preg_replace_callback('/\b(\d+)\.(\d+)\b/', function($m){
$_r=$m[1]; for($i=1; $i<$m[2]; $i++) $_r .= '+' . $m[1] ; return $_r; }, $first);
print_r($second);
Output:
Array
(
[0] => 10+10+6
[1] => 5+5+5+2+2
)
We use this regex /\b(\d+)\.(\d+)\b/ where we match digits before and after DOT separately and capture them in 2 captured groups. Then in callback function we loop through 2nd captured group and construct our output by appending + and 1st captured group.
Here's a solution using regular expressions and various functions. There are many ways to accomplish what you're asking, and this is just one of them. I'm sure this could even be improved upon, but here it is:
$first = array("10.2+5","5.3+2.2");
$second = array();
$pattern = '/(\d+)\.(\d)/';
foreach($first as $item){
$parts = explode('+',$item);
$str = '';
foreach($parts as $part){
if(strlen($str)>0) $str .= '+';
if(preg_match_all($pattern, $part, $matches)){
$str .= implode("+", array_fill(0,$matches[2][$i], $matches[1][$i]));
}else{
$str .= $part;
}
}
$second[] = $str;
}
print_r($second);
Output:
Array
(
[0] => 10+10+5
[1] => 5+5+5+2+2
)
<?php
$first = array("10.2+5","5.3+2");
foreach($first as $term)
{
$second="";
$a=explode("+", $term);
$b=explode(".", $a[0]);
$c=$b[0];
for ($i=0;$i<$b[1];$i++)
$second=$second.$c."+";
echo $second.$a[1]."+";
}
?>

How to create array using customize value?

I have some values below:
11 12 13.
I need to make an array using this value.
array(11,12,13);
I tried this code below :
$selected is the variable that contain the value 11 12 13 //Special Instruction
foreach($selected as $key=>$val)
{
$sel.=$val;
$sel.=",";
}
$str = rtrim($sel,',');
// echo $str;
$shortlist = array_map('trim', explode(',',$str));
I need help to make an array like array(11,12,13).Any idea?
You can use explode here. split is deprecated in latest version.
$str = "11 12 13";
$array = explode(" ",$str);
try str_split see http://www.php.net/manual/en/function.str-split.php
$str = "111213";
$array = str_split($str, 2);
print_r($array);
output :
Array
(
[0] => 11
[1] => 12
[2] => 13
)
$values = explode(' ', "11 12 13");
// if there is no space, you can do it like this
$strLen = strlen($string);
$i = 0;
while($i < $strLen) {
$myArr[] = substr($string, $i, 2);
$i += 2;
}
print_r($myArr);
$selected = "11 12 13";
print_r (explode(" ",$selected));

Efficient check for array items in a string

I have an array like:
arr = array("*" , "$" , "and" , "or" , "!" ,"/");
and another string like :
string = "this * is very beautiful but $ is more important in life.";
I'm looking the most efficient way with the lowest cost to find the member of the array in this string. Also I need to have an array in result that can show which members exist in the string.
The easiest way is using a for loop but I believe there should be more efficient ways to do this in PHP.
$arr=array("*" , "$" , "#" , "!");
$r = '~[' . preg_quote(implode('', $arr)) . ']~';
$str = "this * is very beautiful but $ is more important in life.";
preg_match_all($r, $str, $matches);
echo 'The following chars were found: ' . implode(', ', $matches[0]);
If you are looking for the most efficient way, the result of the following code is:
preg:1.03257489204
array_intersect:2.62625193596
strpos:0.814728021622
It looks like looping the array and matching using strpos is the most efficient way.
$arr=array("*" , "$" , "#" , "!");
$string="this * is very beautiful but $ is more important in life.";
$time = microtime(true);
for ($i=0; $i<100000; $i++){
$r = '~[' . preg_quote(implode('', $arr)) . ']~';
$str = "this * is very beautiful but $ is more important in life.";
preg_match_all($r, $str, $matches);
}
echo "preg:". (microtime(true)-$time)."\n";
$time = microtime(true);
for ($i=0; $i<100000; $i++){
$str = str_split($string);
$out = array_intersect($arr, $str);
}
echo "array_intersect:". (microtime(true)-$time)."\n";
$time = microtime(true);
for ($i=0; $i<100000; $i++){
$res = array();
foreach($arr as $a){
if(strpos($string, $a) !== false){
$res[] = $a;
}
}
}
echo "strpos:". (microtime(true)-$time)."\n";
You can use array_insersect
$string = "this * is very beautiful but $ is more important in life.";
$arr=array("*" , "$" , "#" , "!");
$str = str_split($string);
$out = array_intersect($arr, $str);
print_r($out);
This code will produce the following output
Array ( [0] => * [1] => $ )

PHP string manipulation, inside the string

I have string:
ABCDEFGHIJK
And I have two arrays of positions in that string that I want to insert different things to.
Array
(
[0] => 0
[1] => 5
)
Array
(
[0] => 7
[1] => 9
)
Which if I decided to add the # character and the = character, it'd produce:
#ABCDE=FG#HI=JK
Is there any way I can do this without a complicated set of substr?
Also, # and = need to be variables that can be of any length, not just one character.
You can use string as array
$str = "ABCDEFGH";
$characters = preg_split('//', $str, -1);
And afterwards you array_splice to insert '#' or '=' to position given by array
Return the array back to string is done by:
$str = implode("",$str);
This works for any number of characters (I am using "#a" and "=b" as the character sequences):
function array_insert($array,$pos,$val)
{
$array2 = array_splice($array,$pos);
$array[] = $val;
$array = array_merge($array,$array2);
return $array;
}
$s = "ABCDEFGHIJK";
$arr = str_split($s);
$arr_add1 = array(0=>0, 1=>5);
$arr_add2 = array(0=>7, 1=>9);
$char1 = '#a';
$char2 = '=b';
$arr = array_insert($arr, $arr_add1[0], $char1);
$arr = array_insert($arr, $arr_add1[1] + strlen($char1), $char2);
$arr = array_insert($arr, $arr_add2[0]+ strlen($char1)+ strlen($char2), $char1);
$arr = array_insert($arr, $arr_add2[1]+ strlen($char1)+ strlen($char2) + strlen($char1), $char2);
$s = implode("", $arr);
print_r($s);
There is an easy function for that: substr_replace. But for this to work, you would have to structure you array differently (which would be more structured anyway), e.g.:
$replacement = array(
0 => '#',
5 => '=',
7 => '#',
9 => '='
);
Then sort the array by keys descending, using krsort:
krsort($replacement);
And then you just need to loop over the array:
$str = "ABCDEFGHIJK";
foreach($replacement as $position => $rep) {
$str = substr_replace($str, $rep, $position, 0);
}
echo $str; // prints #ABCDE=FG#HI=JK
This works by inserting the replacements starting from the end of string. And it would work with any replacement string without having to determine the length of that string.
Working DEMO

Most efficient way to delimit key

Say I have a string of 16 numeric characters (i.e. 0123456789012345) what is the most efficient way to delimit it into sets like : 0123-4567-8901-2345, in PHP?
Note: I am rewriting an existing system that is painfully slow.
Use str_split():
$string = '0123456789012345';
$sets = str_split($string, 4);
print_r($sets);
The output:
Array
(
[0] => 0123
[1] => 4567
[2] => 8901
[3] => 2345
)
Then of course to insert hyphens between the sets you just implode() them together:
echo implode('-', $sets); // echoes '0123-4567-8901-2345'
If you are looking for a more flexible approach (for e.g. phone numbers), try regular expressions:
preg_replace('/^(\d{4})(\d{4})(\d{4})(\d{4})$/', '\1-\2-\3-\4', '0123456789012345');
If you can't see, the first argument accepts four groups of four digits each. The second argument formats them, and the third argument is your input.
This is a bit more general:
<?php
// arr[string] = strChunk(string, length [, length [...]] );
function strChunk() {
$n = func_num_args();
$str = func_get_arg(0);
$ret = array();
if ($n >= 2) {
for($i=1, $offs=0; $i<$n; ++$i) {
$chars = abs( func_get_arg($i) );
$ret[] = substr($str, $offs, $chars);
$offs += $chars;
}
}
return $ret;
}
echo join('-', strChunk('0123456789012345', 4, 4, 4, 4) );
?>

Categories