How can I avoid a str_split error in php? - php

I'm trying to split a variable at every character, but I ran across this error:
Warning: str_split() expects parameter 2 to be long, string
The code is:
$split = str_split($num, "");
With $num being taken from the url, which only consist of numbers.
How can fix this?

The second parameter should be a number like this
<?php
$num = 100;
$split = str_split($num, 1);
print_r($split);
RESULT:
Array
(
[0] => 1
[1] => 0
[2] => 0
)
In fact you can leave the second parameter out if it is a 1 like this
<?php
$num = 100;
$split = str_split($num);
print_r($split);
And you will get the same result

As you said split a variable at every character you can just run
$split = str_split($num);
Make sure $num in not empty
Syntax str_split(string,length)
Example
<?php
print_r(str_split("1234"));
?>
Outputs - Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 4 )

You can use this:
$splitText = 1223;
$split = str_split((string) $splitText); //only on php 7
var_dump($split);
you will get this:
array(4) {
[0]=>
string(1) "1"
[1]=>
string(1) "2"
[2]=>
string(1) "2"
[3]=>
string(1) "3"
}
Usage: array str_split ( string $string [, int $split_length = 1 ] ), but check the manual.

Related

PHP - Splitting string lines up into two variables

Not sure how I would do this but if someone could point me in the right track that'll be great, basically I've got a lone line of text in a variable which looks like this:
Lambo 1; Trabant 2; Car 3;
Then I want to split "Lambo" to it's own variable then "1" to it's own variable, and repeat for the others. How would I go and do this?
I know about explode() but not sure how I would do it to split the variable up twice etc.
As requested in the comments my desired output would be like this:
$Item = "Lambo"
$Quantity = 1
Then echo them out and go back to top of loop for example and do the same for the Trabant and Car
<?php
$in = "Lambo 1; Trabant 2; Car 3;";
foreach (explode(";", $in) as $element) {
$element = trim($element);
if (strpos($element, " ") !== false ) {
list($car, $number) = explode(" ", $element);
echo "car: $car, number: $number";
}
}
You can use explode to split the input on each ;, loop over the results and then split over each .
You can use preg_split and iterate over the array by moving twice.
$output = preg_split("/ (;|vs) /", $input);
You could use preg_match_all for getting those parts:
$line = "Lambo 1; Trabant 2; Car 3;";
preg_match_all("/[^ ;]+/", $line, $matches);
$matches = $matches[0];
With that sample data, the $matches array will look like this:
Array ( "Lambo", "1", "Trabant", "2", "Car", "3" )
$new_data="Lambo 1;Trabant 2;Car 3;" ;
$new_array=explode(";", $new_data);
foreach ($new_array as $key ) {
# code...
$final_data=explode(" ", $key);
if(isset($final_data[0])){ echo "<pre>".$final_data[0]."</pre>";}
if(isset($final_data[1])){echo "<pre>".$final_data[1]."</pre>";}
}
This places each word and number in a new key of the array if you need to acess them seperatly.
preg_match_all("/(\w+) (\d+);/", $input_lines, $output_array);
Click preg_match_all
http://www.phpliveregex.com/p/fM8
Use a global regular expression match:
<?php
$subject = 'Lambo 1; Trabant 2; Car 3;';
$pattern = '/((\w+)\s+(\d+);\s?)+/Uu';
preg_match_all($pattern, $subject, $tokens);
var_dump($tokens);
The output you get is:
array(4) {
[0] =>
array(3) {
[0] =>
string(8) "Lambo 1;"
[1] =>
string(10) "Trabant 2;"
[2] =>
string(6) "Car 3;"
}
[1] =>
array(3) {
[0] =>
string(8) "Lambo 1;"
[1] =>
string(10) "Trabant 2;"
[2] =>
string(6) "Car 3;"
}
[2] =>
array(3) {
[0] =>
string(5) "Lambo"
[1] =>
string(7) "Trabant"
[2] =>
string(3) "Car"
}
[3] =>
array(3) {
[0] =>
string(1) "1"
[1] =>
string(1) "2"
[2] =>
string(1) "3"
}
}
In there the elements 2 and 3 hold exactly the tokens you are looking for.

I want to explode a variable in a little different way [duplicate]

This question already has answers here:
How can I use str_getcsv() and ignore commas between quotes?
(1 answer)
REGEX: Splitting by commas that are not in single quotes, allowing for escaped quotes
(4 answers)
Closed 6 months ago.
I have this variable.
$var = "A,B,C,D,'1,2,3,4,5,6',E,F";
I want to explode it so that I get the following array.
array(
[0] => A,
[1] => B,
[2] => C,
[3] => D,
[4] => 1,2,3,4,5,6,
[5] => E,
[6] => F
);
I used explode(',',$var) but I am not getting my desired output. Any suggestions?
There is an existing function that can parse your comma-separated string. The function is str_getcsv
It's signature is like so:
array str_getcsv ( string $input [, string $delimiter = "," [, string $enclosure = '"' [, string $escape = "\\" ]]] )
Your only change would be to change the 3rd variable, the enclosure, to single quotes rather than the default double quotes.
Here is a sample.
$var = "A,B,C,D,'1,2,3,4,5,6',E,F";
$array = str_getcsv($var,',',"'");
If you var_dump the array, you'll get the format you wanted:
array(7) {
[0]=>
string(1) "A"
[1]=>
string(1) "B"
[2]=>
string(1) "C"
[3]=>
string(1) "D"
[4]=>
string(11) "1,2,3,4,5,6"
[5]=>
string(1) "E"
[6]=>
string(1) "F"
}
Simply use preg_match_all with the following regex as follows
preg_match_all("/(?<=').*(?=')|\w+/",$var,$m);
print_r($m[0]);
Regex Explanation :
(?<=').*(?=') Capture each and every character within '(quotes)
|\w+ |(OR) Will grab rest of the characters except ,
Demo
Regex
Although preg_split along with array_map is working very good, see below an example using explode and trim
$var = "A,B,C,D,'1,2,3,4,5,6',E,F";
$a = explode("'",$var);
//print_r($a);
/*
outputs
Array
(
[0] => A,B,C,D,
[1] => 1,2,3,4,5,6
[2] => ,E,F
)
*/
$firstPart = explode(',',trim($a[0],',')); //take out the trailing comma
/*
print_r($firstPart);
outputs
Array
(
[0] => A
[1] => B
[2] => C
[3] => D
)
*/
$secondPart = array($a[1]);
$thirdPart = explode(',',trim($a[2],',')); //tale out the leading comma
/*
print_r($thirdPart);
Array
(
[0] => E
[1] => F
)
*/
$fullArray = array_merge($firstPart,$secondPart,$thirdPart);
print_r($fullArray);
/*
ouputs
Array
(
[0] => A
[1] => B
[2] => C
[3] => D
[4] => 1,2,3,4,5,6
[5] => E
[6] => F
)
*/
You need to explode the string to array.
But, you need commas after every element except last one.
Here is working example:
<?php
$var = "A,B,C,D,'1,2,3,4,5,6',E,F";
$arr = explode("'", $var);
$num = ! empty($arr[1]) ? str_replace(',', '_', $arr[1]) : '';
$nt = $arr[0] . $num . $arr[2];
$nt = explode(',', $nt);
$len = count($nt);
$na = array();
$cnt = 0;
foreach ($nt as $v) {
$v = str_replace('_', ',', $v);
$v .= ($cnt != $len - 1) ? ',' : '';
$na[] = $v;
++$cnt;
}
Demo
$var = "A,B,C,D,'1,2,3,4,5,6',E,F";
$arr = preg_split("/(,)(?=(?:[^']|'[^']*')*$)/",$var);
foreach ($arr as $data) {
$requiredData[] = str_replace("'","",$data);
}
echo '<pre>';
print_r($requiredData);
Description :
Regular Exp. :-
(?<=').*(?=') => Used to get all characters within single quotes(' '),
|\w+ |(OR) => Used to get rest of characters excepted comma(,)
Then Within foreach loop i'm replacing single quote

How to split PHP string if character count is greater

I have a user input field. It will be a textarea. When user submit the form I want to check if the entered character count is more than 10. If more than 10 I want to split it. Clearly says, if I get a string
$someWords = "Pleasedon'tblowmetopiecesandthis will be a 12345 random.";
Then I want to split this string. Each parts should be maximum of 10 character long. Required result (clean text) should be something like below,
tblowmetop
iecesandth
is will be
a 12345 r
andom
How can I do this in PHP? I have idea about getting count using strlen($string);.
You can use PHPs built-in function chunk_split():
$chunkedString = chunk_split($someWords, 10);
This gives you a string with a line break after each 10 characters.
If you like to get an array with entries of 10 characters each you can use PHPs str_split():
$chunks = str_split($someWords, 10);
PHP has a built-in function called str_split() That splits a string and creates an array.
$arr = str_split($someWords, 10);
This code will create an array of strings, each with a length of 10 characters. The similar function chunk_split() can be used to insert additional content every n characters.
$chunked = chunk_split($someWords, 10);
$chunked is a single string with newlines inserted every 10 characters. This function can be useful for wrapping text for output.
<?php
$str = "Hello Friend";
$arr1 = str_split($str);
$arr2 = str_split($str, 3);
print_r($arr1);
print_r($arr2);
?>
This function counts space(" ") as one character
Output
Array
(
[0] => H
[1] => e
[2] => l
[3] => l
[4] => o
[5] =>
[6] => F
[7] => r
[8] => i
[9] => e
[10] => n
[11] => d
)
Array
(
[0] => Hel
[1] => lo
[2] => Fri
[3] => end
)
http://php.net/manual/en/function.str-split.php
Check this link for more information
Need to remove space use str_replace function before str_split for replace space in string
you could try using recursively
function submystr_to_array($str, $length, $arr_result = array() )
{
$istr_len = strlen($str);
if ( $istr_len == 0 )
return $arr_result;
$result = substr($str, 0, $length);
$tail = substr($str, $length, $istr_len );
if ( $result )
array_push( $arr_result, $result );
if( !$tail )
return $arr_result;
return submystr_to_array( $tail, $length, $arr_result);
}
$mystr = "Pleasedon'tblowmetopiecesandthis will be a 12345 random.";
var_dump( submystr_to_array($mystr, 10) );
result:
array(6) {
[0]=>
string(10) "Pleasedon'"
[1]=>
string(10) "tblowmetop"
[2]=>
string(10) "iecesandth"
[3]=>
string(10) "is will be"
[4]=>
string(10) " a 12345 r"
[5]=>
string(6) "andom."
}

PHP spilt a 4 character string by character

I have string like so $string = 0730 I am looking to spilt this into an array like so:
$string[0] = 0
$string[1] = 7
$string[2] = 3
$string[3] = 0
I have looked into explode, but I do not have a delimiter or would just "" work?
Or is there another php function I should use?
You can just access the string as an array:
$string = "0730";
echo $string[1]; // 7
But if you need an array (for using in array_map or something), use str_split
use str_split() function
$string = '0730';
print_r(str_split($string));
output:
Array
(
[0] => 0
[1] => 7
[2] => 3
[3] => 0
)
You can use the str_split() function:
$string = "0730";
var_dump(str_split($string));
which gives you:
array(4) {
[0]=>
string(1) "0"
[1]=>
string(1) "7"
[2]=>
string(1) "3"
[3]=>
string(1) "0"
}

Explode comma separated integers to intvals? [duplicate]

This question already has answers here:
Convert a comma-delimited string into array of integers?
(17 answers)
Closed 9 years ago.
Say I have a string like so $thestring = "1,2,3,8,2".
If I explode(',', $thestring) it, I get an array of strings. How do I explode it to an array of integers instead?
array_map also could be used:
$s = "1,2,3,8,2";
$ints = array_map('intval', explode(',', $s ));
var_dump( $ints );
Output:
array(5) {
[0]=> int(1)
[1]=> int(2)
[2]=> int(3)
[3]=> int(8)
[4]=> int(2)
}
Example codepad.
Use something like this:
$data = explode( ',', $thestring );
array_walk( $data, 'intval' );
http://php.net/manual/en/function.array-walk.php
For the most part you shouldn't really need to (PHP is generally good with handling casting strings and floats/ints), but if it is absolutely necessary, you can array_walk with intval or floatval:
$arr = explode(',','1,2,3');
// use floatval if you think you are going to have decimals
array_walk($arr,'intval');
print_r($arr);
Array
(
[0] => 1
[1] => 2
[2] => 3
)
If you need something a bit more verbose, you can also look into settype:
$arr = explode(",","1,2,3");
function fn(&$a){settype($a,"int");}
array_walk($f,"fn");
print_r($f);
Array
(
[0] => 1
[1] => 2
[2] => 3
)
That could be particularly useful if you're trying to cast dynamically:
class Converter {
public $type = 'int';
public function cast(&$val){ settype($val, $this->type); }
}
$c = new Converter();
$arr = explode(",","1,2,3,0");
array_walk($arr,array($c, 'cast'));
print_r($arr);
Array
(
[0] => 1
[1] => 2
[2] => 3
[3] => 0
)
// now using a bool
$c->type = 'bool';
$arr = explode(",","1,2,3,0");
array_walk($arr,array($c, 'cast'));
var_dump($arr); // using var_dump because the output is clearer.
array(4) {
[0]=>
bool(true)
[1]=>
bool(true)
[2]=>
bool(true)
[3]=>
bool(false)
}
Since $thestring is an string then you will get an array of strings.
Just add (int) in front of the exploded values.
Or use the array_walk function:
$arr = explode(',', $thestring);
array_walk($arr, 'intval');
$thestring = "1,2,3,8,a,b,2";
$newArray = array();
$theArray = explode(",", $thestring);
print_r($theArray);
foreach ($theArray as $theData) {
if (is_numeric($theData)) {
$newArray[] = $theData;
}
}
print_r($newArray);
// Output
Original array
Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 8 [4] => a [5] => b [6] => 2 )
Numeric only array
Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 8 [4] => 2 )
$arr=explode(',', $thestring);
$newstr = '';
foreach($arr as $key=>$val){
$newstr .= $val;
}

Categories