I have $value = "10,120,152" in string, now i want to put each number in separate variable like $a = 10; $b = 120; $c = 152;
so basically what i am asking is that how to separate , from the numbers in a string.
If the separator is always a , than using explode makes sense. If the separator varies though you could use a regex.
$value = "10,120,152";
preg_match_all('/(\d+)/', $value, $matches);
print_r($matches[1]);
Output:
Array
(
[0] => 10
[1] => 120
[2] => 152
)
Demo: https://eval.in/483906
That \d+ is all continuos numbers.
Regex101 Demo: https://regex101.com/r/rP2bV1/1
A third approach would be using str_getcsv.
$value = "10,120,152";
$numbers = str_getcsv($value, ',');
print_r($numbers);
Output:
Array
(
[0] => 10
[1] => 120
[2] => 152
)
Demo: https://eval.in/483907
$exploded = explode("," , $values);
var_dump($exploded);
Explode(string $delimiter , string $string [, int $limit ])
You can use explode(), it will return an array with the numbers.
$array = explode(',', $value);
Check this one using list
$value = "10,120,152";
$variables = explode("," , $values);
$variables = array_map('intval', $variables);//If you want integers add this line
list($a, $b, $c) = $variables;
Related
It can distinguishes between decimal and '-'
$str = "1995-25";
$pat = sscanf( $str , "%d-%d);
print_r($pat);
It can also distinguish first '-' and following string
$str = "-of";
$pattern = sscanf ( $str , "-%s" );
print_r ( $pattern );
but when it comes to signify '-' in middle of a string
it assumes '-' as string
and more surprisingly the first %s reads it to the last
even considering 4 as string
$str = '-of-america-4';
$pat = sscanf ($str , "-%s-%s-%d");
print_r($pat);
// outputs [0] => of-america-4
%s is a greedy match, you could use %[^-]
<?php
$str = '-of-america-4';
$pat = sscanf($str , '-%[^-]-%[^-]-%d');
print_r($pat);
Array
(
[0] => of
[1] => america
[2] => 4
)
How to convert this string
*|text:student:required|*
( * and | is part of string ) into array like this
['text' ,'student','required']
try the following:
$str = '*|text:student:required|*';
$str = preg_replace("/[|*]/", '', $str);
$arr = explode(':', $str);
this simply removes the | AND * from the string using preg_replace() and the turns the string into an array using explode
Here you go:
$str = "|text:student:required|";
$str = trim($str,"|");
$str = trim($str,"*");
$x = explode(':',$str);
print_r($x);die;
The shortest one with preg_split function:
$s = '*|text:student:required|* ';
$result = preg_split('/[*:| ]+/', $s, -1, PREG_SPLIT_NO_EMPTY);
print_r($result);
The output:
Array
(
[0] => text
[1] => student
[2] => required
)
$string = "*|text:student:required|";
$string = str_replace("*", "", str_replace("|","", $string));
$array = explode(':', $string);
I need some help, is it possible to explode like this?
I have a string 45-test-sample, is it possible to have
[0]=>string == "45"
[1]=>string == "test-sample"
How can it be done?
print_r(explode('-', $string, 2)); // take some help from the limit parameter
According to the PHP manual for explode
If limit is set and positive, the returned array will contain a maximum of limit elements with the last element containing the rest of string.
Output:
Array
(
[0] => 45
[1] => test-sample
)
Explode has a limit parameter.
$array = explode('-', $text, 2);
try this
$str = "45-test-sample";
$arr = explode('-', $str, 2);
print_r($arr);
OUTPUT :
Array
(
[0] => 45
[1] => test-sample
)
Demo
Try with exact output using list.
<?php
$str = "45-test-sample";
list($a,$b) = explode('-', $str, 2);
$arr=Array();
$arr=['0'=>"String == ".$a,'1'=>"String == ".$b];
print_r($arr);
?>
Output:
Array
(
[0] => String == 45
[1] => String == test-sample
)
DEMO
I'm using PHP, and I get a string from a db with a struct similar to this:
$string = "a:b;c:d;e:f;g:h;" and so on, where a, b, c.. are variables,
a,c and e couldn't be a continuous number, they can be numbers from 1 to 500.
I need to convert this string into an array with this format:
$array [a] == ("b");
$array [c] == ("d");
$array [e] == ("f");
etc...
But I don't know how to get two substring from string (double dot separated, and dot comma separated) and put it into a 2 D string.
Thanks you in advance
To manipulate the keys and the values of the resulting array without foreach loop, you can use array_reduce:
$string = "a:b;c:d;e:f;g:h;";
$array = array_reduce( array_filter( explode( ';', $string ) ), function( $result, $item ) {
$tmp = explode( ':', $item );
$result[$tmp[0]] = $tmp[1];
return $result;
});
output:
Array (
[a] => b
[c] => d
[e] => f
[g] => h
)
not sure what you are asking,but this may helps you
$re = '/(.?):(.?)/';
$str = 'a:b;c:d;e:f;g:h;';
preg_match_all($re, $str, $matches);
print_r(array_combine($matches[1],$matches[2]));
output:
(
[a] => b
[c] => d
[e] => f
[g] => h
)
use explode() which will split a string into an array based on the specified delimiter.
$string = "a:b;c:d;e:f;g:h;";
$temparray = explode(';', $string);
//$temparray now looks like ['a:b', 'c:d', 'e:f']
//use explode() again in a loop to split up each index
$finalarray = array();
foreach($temparray as $arr){
$splitarr = explode(':', $arr);
//$splitarr will look something like ['a', 'b']
//use those values to set the indexes in your final array
$finalarray[$splitarr[0]] = $splitarr[1];
}
$finalarray=array_filter($finalarray);//to remove null values
//print_r($finalarray);
NOTE: Just FYI, because of the trailing ; in your string, you may end up with an extra empty index at the end of your arrays, hence the array_filter() call, thanks #FerozAkbar
$str = "This is a string";
$words = explode(" ", $str);
Works fine, but spaces still go into array:
$words === array ('This', 'is', 'a', '', '', '', 'string');//true
I would prefer to have words only with no spaces and keep the information about the number of spaces separate.
$words === array ('This', 'is', 'a', 'string');//true
$spaces === array(1,1,4);//true
Just added: (1, 1, 4) means one space after the first word, one space after the second word and 4 spaces after the third word.
Is there any way to do it fast?
Thank you.
For splitting the String into an array, you should use preg_split:
$string = 'This is a string';
$data = preg_split('/\s+/', $string);
Your second part (counting spaces):
$string = 'This is a string';
preg_match_all('/\s+/', $string, $matches);
$result = array_map('strlen', $matches[0]);// [1, 1, 4]
Here is one way, splitting the string and running a regex once, then parsing the results to see which segments were captured as the split (and therefore only whitespace), or which ones are words:
$temp = preg_split('/(\s+)/', $str, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);
$spaces = array();
$words = array_reduce( $temp, function( &$result, $item) use ( &$spaces) {
if( strlen( trim( $item)) === 0) {
$spaces[] = strlen( $item);
} else {
$result[] = $item;
}
return $result;
}, array());
You can see from this demo that $words is:
Array
(
[0] => This
[1] => is
[2] => a
[3] => string
)
And $spaces is:
Array
(
[0] => 1
[1] => 1
[2] => 4
)
You can use preg_split() for the first array:
$str = 'This is a string';
$words = preg_split('#\s+#', $str);
And preg_match_all() for the $spaces array:
preg_match_all('#\s+#', $str, $m);
$spaces = array_map('strlen', $m[0]);
Another way to do it would be using foreach loop.
$str = "This is a string";
$words = explode(" ", $str);
$spaces=array();
$others=array();
foreach($words as $word)
{
if($word==' ')
{
array_push($spaces,$word);
}
else
{
array_push($others,$word);
}
}
Here are the results of performance tests:
$str = "This is a string";
var_dump(time());
for ($i=1;$i<100000;$i++){
//Alma Do Mundo - the winner
$rgData = preg_split('/\s+/', $str);
preg_match_all('/\s+/', $str, $rgMatches);
$rgResult = array_map('strlen', $rgMatches[0]);// [1,1,4]
}
print_r($rgData); print_r( $rgResult);
var_dump(time());
for ($i=1;$i<100000;$i++){
//nickb
$temp = preg_split('/(\s+)/', $str, -1,PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);
$spaces = array();
$words = array_reduce( $temp, function( &$result, $item) use ( &$spaces) {
if( strlen( trim( $item)) === 0) {
$spaces[] = strlen( $item);
} else {
$result[] = $item;
}
return $result;
}, array());
}
print_r( $words); print_r( $spaces);
var_dump(time());
int(1378392870)
Array
(
[0] => This
[1] => is
[2] => a
[3] => string
)
Array
(
[0] => 1
[1] => 1
[2] => 4
)
int(1378392871)
Array
(
[0] => This
[1] => is
[2] => a
[3] => string
)
Array
(
[0] => 1
[1] => 1
[2] => 4
)
int(1378392873)
$financialYear = 2015-2016;
$test = explode('-',$financialYear);
echo $test[0]; // 2015
echo $test[1]; // 2016
Splitting with regex has been demonstrated well by earlier answers, but I think this is a perfect case for calling ctype_space() to determine which result array should receive the encountered value.
Code: (Demo)
$string = "This is a string";
$words = [];
$spaces = [];
foreach (preg_split('~( +)~', $string, null, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE) as $s) {
if (ctype_space($s)) {
$spaces[] = strlen($s);
} else {
$words[] = $s;
}
}
var_export([
'words' => $words,
'spaces' => $spaces
]);
Output:
array (
'words' =>
array (
0 => 'This',
1 => 'is',
2 => 'a',
3 => 'string',
),
'spaces' =>
array (
0 => 1,
1 => 1,
2 => 4,
),
)
If you want to replace the piped constants used by preg_split() you can just use 3 (Demo). This represents PREG_SPLIT_NO_EMPTY which is 1 plus PREG_SPLIT_DELIM_CAPTURE which is 2. Be aware that with this reduction in code width, you also lose code readability.
preg_split('~( +)~', $string, -1, 3)
What about this? Does someone care to profile this?
$str = str_replace(["\t", "\r", "\r", "\0", "\v"], ' ', $str); // \v -> vertical space, see trim()
$words = explode(' ', $str);
$words = array_filter($words); // there would be lots elements from lots of spaces so skip them.