Search in a string and create an array in PHP - php

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);

Related

Comma-separated string to associative array with lowercase keys

I have a string like this:
$string = 'Apple, Orange, Lemone';
I want to make this string to:
$array = array('apple'=>'Apple', 'orang'=>'Orange', 'lemone'=>'Lemone');
How to achieve this?
I used the explode function like this:
$string = explode(',', $string );
But that only gives me this:
Array ( [0] => Apple [1] => Orange [2] => Lemone )
Somebody says this question is a duplicate of this SO question: Split a comma-delimited string into an array?
But that question is not addressing my problem. I have already reached the answer of that question, please read my question. I need to change that result array's key value and case. see:
Array
(
[0] => 9
[1] => admin#example.com
[2] => 8
)
to like this
Array
(
[9] => 9
[admin#example.com] => admin#example.com
[8] => 8
)
You may try :
$string = 'Apple, Orange, Lemone';
$string = str_replace(' ', '', $string);
$explode = explode(',',$string);
$res = array_combine($explode,$explode);
echo '<pre>';
print_r($res);
echo '</pre>';
Or if you need to make lower case key for resulting array use following :
echo '<pre>';
print_r(array_change_key_case($res,CASE_LOWER));
echo '</pre>';
<?php
$string = 'Apple, Orange, Lemone'; // your string having space after each value
$string =str_replace(' ', '', $string); // removing blank spaces
$array = explode(',', $string );
$final_array = array_combine($array, $array);
$final_array = array_change_key_case($final_array, CASE_LOWER); // Converting all the keys to lower case based on your requiment
echo '<pre>';
print_r($final_array);
?>
You can use array functions such as array_combine, and array_values
$string = 'Apple, Orange, Lemone';
$arr = explode(', ', $string);
$assocArr = array_change_key_case(
array_combine(array_values($arr), $arr)
);
<?php
$string = 'Apple, Orange, Lemone';
$array = explode(', ', $string);
print_r($array);
output will be
Array
(
[0] => Apple
[1] => Orange
[2] => Lemone
)
Now
$ar = array();
foreach ($array as $value) {
$ar[$value] = $value;
}
print_r($ar);
Your Desire Output:
Array
(
[Apple] => Apple
[Orange] => Orange
[Lemone] => Lemone
)
$valuesInArrayWithSpace = explode("," $string);
$finalArray = [];
foreach ($ValuesInArrayWitchSpace as $singleItem) {
$finalArray[trim(strtolower($singleItem))] = trim($singleItem);
}
This way you'll have what you need:
$lowerString = strtolower($string);
$values = explode(', ', $string);
$keys = explode(', ', $lowerString);
$array = array_combine($keys, $values);
print_r($array);
Or...
$csvdata = str_getcsv('Apple,Orange,Lemone');
$arr = [];
foreach($csvdata as $a) {
$arr[strtolower(trim($a))] = $a;
}
print_r($arr);
use array_flip to change the values as key and use array_combine
<?php
$string = 'Apple, Orange, Lemone';
$array = explode(', ', $string);
$new_array =array_flip($array);
$final_array = array_combine($new_array,$array)
print_r($final_array );
?>
A clean, functional-style approach can use array_reduce() after splitting on commas followed by spaces.
Before pushing the new associative values into the result array, change the key to lowercase.
Code: (Demo)
$string = 'Apple, Orange, Lemone';
var_export(
array_reduce(
explode(', ', $string),
fn($result, $v) =>
$result + [strtolower($v) => $v],
[]
)
);
Output:
array (
'apple' => 'Apple',
'orange' => 'Orange',
'lemone' => 'Lemone',
)

Explode function side by side same character

I have an string
$str = 'one,,two,three,,,,,four';
I want to array like this(output of print_r)
Array ( [0] => one,two,three,four )
My code is
$str = 'one,,two,three,,,,,four';
$str_array = explode(',', $str);
print_r($str_array);
But not working Because multiple commas side by side.How can i solve this problem?
You can used array_filter function to removed empty element from array.
So your code should be:
$str = 'one,,two,three,,,,,four';
$str_array = array_filter(explode(',', $str));
print_r($str_array);
Edited Code
$str = 'one,,two,three,,,,,four';
$str_array = implode(',',array_filter(explode(',', $str)));
echo $str_array; // you will get one,two,three,four
You can remove multiple comma using preg_replace as
$str = 'one,,two,three,,,,,four';
echo $str_new = preg_replace('/,+/', ',', $str);// one,two,three,four
$str_array = explode(' ', $str_new);
print_r($str_array);//Array ( [0] => one,two,three,four )
try this
<?php
$string = 'one,,two,three,,,,,four';
$new_array = array_filter(explode(',', $string));
$final_array[] = implode(',',$new_array);
print_r($final_array);
?>
OUTPUT: Array ( [0] => one,two,three,four )
<?php
$string = 'one,,two,three,,,,,four';
$result = array(preg_replace('#,+#', ',', $string));
print_r($result);
Output:
Array ( [0] => one,two,three,four )

separate special characters from numbers in string in php

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;

php explode: split string into words by using space a delimiter

$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.

how to convert a string to an array in php [duplicate]

This question already has answers here:
Creating an array from a string separated by spaces
(7 answers)
Closed 1 year ago.
how to convert a string in array in php i.e
$str="this is string";
should be like this
arr[0]=this
arr[1]=is
arr[2]=string
The str_split($str, 3); splits the string in 3 character word but I need to convert the string after whitespace in an array.
Use explode function
$array = explode(' ', $string);
The first argument is delimiter
With explode function of php
$array=explode(" ",$str);
This is a quick example for you http://codepad.org/Pbg4n76i
<?php
$str = "Hello Friend";
$arr1 = str_split($str);
$arr2 = str_split($str, 3);
print_r($arr1);
print_r($arr2);
?>
try json_decode like so
<?php
$var = '["SupplierInvoiceReconciliation"]';
$var = json_decode($var, TRUE);
print_r($var);
?>
Take a look at the explode function.
<?php
// Example 1
$pizza = "piece1 piece2 piece3 piece4 piece5 piece6";
$pieces = explode(" ", $pizza);
echo $pieces[0]; // piece1
echo $pieces[1]; // piece2
?>
There is a function in PHP specifically designed for that purpose, str_word_count(). By default it does not take into account the numbers and multibyte characters, but they can be added as a list of additional characters in the charlist parameter. Charlist parameter also accepts a range of characters as in the example.
One benefit of this function over explode() is that the punctuation marks, spaces and new lines are avoided.
$str = "1st example:
Alte Füchse gehen schwer in die Falle. ";
print_r( str_word_count( $str, 1, '1..9ü' ) );
/* output:
Array
(
[0] => 1st
[1] => example
[2] => Alte
[3] => Füchse
[4] => gehen
[5] => schwer
[6] => in
[7] => die
[8] => Falle
)
*/
explode() might be the function you are looking for
$array = explode(' ',$str);
explode — Split a string by a string
Syntax :
array explode ( string $delimiter , string $string [, int $limit = PHP_INT_MAX ] )
$delimiter : based on which you want to split string
$string. : The string you want to split
Example :
// Example 1
$pizza = "piece1 piece2 piece3 piece4 piece5 piece6";
$pieces = explode(" ", $pizza);
echo $pieces[0]; // piece1
echo $pieces[1]; // piece2
In your example :
$str = "this is string";
$array = explode(' ', $str);
You can achieve this even without using explode and implode function.
Here is the example:
Input:
This is my world
Code:
$part1 = "This is my world";
$part2 = str_word_count($part1, 1);
Output:
Array( [0] => 'This', [1] => 'is', [2] => 'my', [3] => 'world');
here, Use explode() function to convert string into array, by a string
click here to know more about explode()
$str = "this is string";
$delimiter = ' '; // use any string / character by which, need to split string into Array
$resultArr = explode($delimiter, $str);
var_dump($resultArr);
Output :
Array
(
[0] => "this",
[1] => "is",
[2] => "string "
)
it is same as the requirements:
arr[0]="this";
arr[1]="is";
arr[2]="string";

Categories