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."
}
Related
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.
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
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;
}
I am trying to split a string into an array of word pairs in PHP. So for example if you have the input string:
"split this string into word pairs please"
the output array should look like
Array (
[0] => split this
[1] => this string
[2] => string into
[3] => into word
[4] => word pairs
[5] => pairs please
[6] => please
)
some failed attempts include:
$array = preg_split('/\w+\s+\w+/', $string);
which gives me an empty array, and
preg_match('/\w+\s+\w+/', $string, $array);
which splits the string into word pairs but doesn't repeat the word. Is there an easy way to do this? Thanks.
Why not just use explode ?
$str = "split this string into word pairs please";
$arr = explode(' ',$str);
$result = array();
for($i=0;$i<count($arr)-1;$i++) {
$result[] = $arr[$i].' '.$arr[$i+1];
}
$result[] = $arr[$i];
Working link
If you want to repeat with a regular expression, you'll need some sort of look-ahead or look-behind. Otherwise, the expression will not match the same word multiple times:
$s = "split this string into word pairs please";
preg_match_all('/(\w+) (?=(\w+))/', $s, $matches, PREG_SET_ORDER);
$a = array_map(
function($a)
{
return $a[1].' '.$a[2];
},
$matches
);
var_dump($a);
Output:
array(6) {
[0]=>
string(10) "split this"
[1]=>
string(11) "this string"
[2]=>
string(11) "string into"
[3]=>
string(9) "into word"
[4]=>
string(10) "word pairs"
[5]=>
string(12) "pairs please"
}
Note that it does not repeat the last word "please" as you requested, although I'm not sure why you would want that behavior.
You could explode the string and then loop through it:
$str = "split this string into word pairs please";
$strSplit = explode(' ', $str);
$final = array();
for($i=0, $j=0; $i<count($strSplit); $i++, $j++)
{
$final[$j] = $strSplit[$i] . ' ' . $strSplit[$i+1];
}
I think this works, but there should be a way easier solution.
Edited to make it conform to OP's spec. - as per codaddict
$s = "split this string into word pairs please";
$b1 = $b2 = explode(' ', $s);
array_shift($b2);
$r = array_map(function($a, $b) { return "$a $b"; }, $b1, $b2);
print_r($r);
gives:
Array
(
[0] => split this
[1] => this string
[2] => string into
[3] => into word
[4] => word pairs
[5] => pairs please
[6] => please
)
How can I explode a string on every third semicolon (;)?
example data:
$string = 'piece1;piece2;piece3;piece4;piece5;piece6;piece7;piece8;';
Desired output:
$output[0] = 'piece1;piece2:piece3;'
$output[1] = 'piece4;piece5;piece6;'
$output[2] = 'piece7;piece8;'
I am sure you can do something slick with regular expressions, but why not just explode the each semicolor and then add them three at a time.
$tmp = explode(";", $string);
$i=0;
$j=0;
foreach($tmp as $piece) {
if(! ($i++ %3)) $j++; //increment every 3
$result[$j] .= $piece;
}
Easiest solution I can think of is:
$chunks = array_chunk(explode(';', $input), 3);
$output = array_map(create_function('$a', 'return implode(";",$a);'), $chunks);
Essentially the same solution as the other ones that explode and join again...
$tmp = explode(";", $string);
while ($tmp) {
$output[] = implode(';', array_splice($tmp, 0, 3));
};
$string = "piece1;piece2;piece3;piece4;piece5;piece6;piece7;piece8;piece9;";
preg_match_all('/([A-Za-z0-9\.]*;[A-Za-z0-9\.]*;[A-Za-z0-9\.]*;)/',$string,$matches);
print_r($matches);
Array
(
[0] => Array
(
[0] => piece1;piece2;piece3;
[1] => piece4;piece5;piece6;
[2] => piece7;piece8;piece9;
)
[1] => Array
(
[0] => piece1;piece2;piece3;
[1] => piece4;piece5;piece6;
[2] => piece7;piece8;piece9;
)
)
Maybe approach it from a different angle. Explode() it all, then combine it back in triples. Like so...
$str = "1;2;3;4;5;6;7;8;9";
$boobies = explode(";", $array);
while (!empty($boobies))
{
$foo = array();
$foo[] = array_shift($boobies);
$foo[] = array_shift($boobies);
$foo[] = array_shift($boobies);
$bar[] = implode(";", $foo) . ";";
}
print_r($bar);
Array
(
[0] => 1;2;3;
[1] => 4;5;6;
[2] => 7;8;9;
)
Here's a regex approach, which I can't say is all too good looking.
$str='';
for ($i=1; $i<20; $i++) {
$str .= "$i;";
}
$split = preg_split('/((?:[^;]*;){3})/', $str, -1,
PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE);
Output:
Array
(
[0] => 1;2;3;
[1] => 4;5;6;
[2] => 7;8;9;
[3] => 10;11;12;
[4] => 13;14;15;
[5] => 16;17;18;
[6] => 19;
)
Another regex approach.
<?php
$string = 'piece1;piece2;piece3;piece4;piece5;piece6;piece7;piece8';
preg_match_all('/([^;]+;?){1,3}/', $string, $m, PREG_SET_ORDER);
print_r($m);
Results:
Array
(
[0] => Array
(
[0] => piece1;piece2;piece3;
[1] => piece3;
)
[1] => Array
(
[0] => piece4;piece5;piece6;
[1] => piece6;
)
[2] => Array
(
[0] => piece7;piece8
[1] => piece8
)
)
Regex Split
$test = ";2;3;4;5;6;7;8;9;10;;12;;14;15;16;17;18;19;20";
// match all groups that:
// (?<=^|;) follow the beginning of the string or a ;
// [^;]* have zero or more non ; characters
// ;? maybe a semi-colon (so we catch a single group)
// [^;]*;? again (catch second item)
// [^;]* without the trailing ; (to not capture the final ;)
preg_match_all("/(?<=^|;)[^;]*;?[^;]*;?[^;]*/", $test, $matches);
var_dump($matches[0]);
array(7) {
[0]=>
string(4) ";2;3"
[1]=>
string(5) "4;5;6"
[2]=>
string(5) "7;8;9"
[3]=>
string(6) "10;;12"
[4]=>
string(6) ";14;15"
[5]=>
string(8) "16;17;18"
[6]=>
string(5) "19;20"
}
<?php
$str = 'piece1;piece2;piece3;piece4;piece5;piece6;piece7;piece8;';
$arr = array_map(function ($arr) {
return implode(";", $arr);
}, array_chunk(explode(";", $str), 3));
var_dump($arr);
outputs
array(3) {
[0]=>
string(20) "piece1;piece2;piece3"
[1]=>
string(20) "piece4;piece5;piece6"
[2]=>
string(14) "piece7;piece8;"
}
Similar to #Sebastian's earlier answer, I recommend preg_split() with a repeated pattern. The difference is that by using a non-capturing group and appending \K to restart the fullstring match, you can spare writting the PREG_SPLIT_DELIM_CAPTURE flag.
Code: (Demo)
$string = 'piece1;piece2;piece3;piece4;piece5;piece6;piece7;piece8;';
var_export(preg_split('/(?:[^;]*;){3}\K/', $string, 0, PREG_SPLIT_NO_EMPTY));
A similar technique for splitting after every 2 things can be found here. That snippet actually writes the \K before the last space character so that the trailing space is consumed while splitting.