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

This question already has answers here:
Convert backslash-delimited string into an associative array
(4 answers)
Closed 2 years ago.
How to convert a string to an array in PHP? I've a string like this:
$str = "php/127/typescript/12/jquery/120/angular/50";
The output:
Array (
[php]=> 127
[typescript]=> 12
[jquery]=> 120
[angular]=> 50
)

You can use preg_match_all (Regular Expression), and array_combine:
RegEx used : ([^\/]*?)\/(\d+), eplanation here (by RegEx101)
$str = "php/127/typescript/12/jquery/120/angular/50";
#match string
preg_match_all("/([^\/]*?)\/(\d+)/", $str, $match);
#then combine match[1] and match[2]
$result = array_combine($match[1], $match[2]);
print_r($result);
Demo (with steps) : https://3v4l.org/blZhU

One approach might be to use preg_match_all to extract the keys and values from the path separately. Then, use array_combine to build the hashmap:
$str = "php/127/typescript/12/jquery/120/angular/50";
preg_match_all("/[^\W\d\/]+/", $str, $keys);
preg_match_all("/\d+/", $str, $vals);
$mapped = array_combine($keys[0], $vals[0]);
print_r($mapped[0]);
This prints:
Array
(
[0] => php
[1] => typescript
[2] => jquery
[3] => angular
)

You can use explode() with for()Loop as below:-
<?php
$str = 'php/127/typescript/12/jquery/120/angular/50';
$list = explode('/', $str);
$list_count = count($list);
$result = array();
for ($i=0 ; $i<$list_count; $i+=2) {
$result[ $list[$i] ] = $list[$i+1];
}
print_r($result);
?>
Output:-
Array
(
[php] => 127
[typescript] => 12
[jquery] => 120
[angular] => 50
)
Demo Here :- https://3v4l.org/8PQhd

Related

How to join a column of values with comma then space? [duplicate]

This question already has answers here:
Implode a column of values from a two dimensional array [duplicate]
(3 answers)
Closed 7 months ago.
I'm trying to loop through an array that I got from preg_match_all result in order to create one string from all results.
Array looks like this:
print_r($matches[0]);
Array
(
[0] => Array
(
[0] => 8147
[1] => 3
)
[1] => Array
(
[0] => 8204
[1] => 20
)
)
And my code:
$found = count($matches[0]);
for ($i = 0; $i <= $found; $i++) {
$string = $matches[0][$i];
}
I would like to get result of $string like this: 8147, 8204.
How I can append $matches[0][0] to $matches[0][1] etc. in string variable using loop?
You can do this some ting like that
$string = "";
foreach($matches[0] as $value) {
$string .= $value[0].", ";
}
$string = rtrim(", ",$string);
With php5.5 and more you can use array_column + implode:
echo implode(', ', array_column($matches, 0));
Try following code. Loop through array and get values
$arr =Array
(
0 => Array
(
0 => 8147,
1 => 3
),
1 => Array
(
0 => 8204,
1 => 20
)
);
$match_array = array();
foreach($arr as $key=>$value)
{
$match_array[] = $value[0];
}
$str = implode(",",$match_array);
echo $str;
DEMO
OR simply use array_column to get specific column as array then use implode
$arr =Array
(
0 => Array
(
0 => 8147,
1 => 3
),
1 => Array
(
0 => 8204,
1 => 20
)
);
$match_array = array_column($arr,0);
$str = implode(",",$match_array);
echo $str;
DEMO
You can use array_column, no need to loop over the array
$result = join(',', array_column($arr, 0));

Remove string start from certain character? [duplicate]

This question already has answers here:
PHP substring extraction. Get the string before the first '/' or the whole string
(14 answers)
Closed 5 years ago.
For example I have an array
$array[] = ['name - ic'];
The result I want is
$new_Array[]=['name'];
How do I remove the string that start from the - since the name and ic will be different for everyone? Anyone can help?
Using explode method you can split string into array.
PHP
<?php
$array[] = ['name - ic'];
$array[] = ['name - bc - de'];
$new_Array = array();
foreach($array as $key=>$values){
foreach($values as $k=>$val){
$str = explode("-",$val);
$new_Array[$key][$k] = trim($str[0]);
}
}
?>
OUTPUT
Array
(
[0] => Array
(
[0] => name
)
[1] => Array
(
[0] => name
)
)
You can use explode function for the same.
$array = array('name - ic','abc - xyz','pqr-stu');
$newArray = array();
foreach($array as $obj):
$temp = explode('-',$obj);
$newArray[] = trim($temp[0]);
endforeach;
print_r($newArray);
Result
Array ( [0] => name [1] => abc [2] => pqr )
Let me know if it not works.

Explode PHP 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

What is the best way to split letters and numbers?

I have this variable:
$str = "w15";
What is the best way to split it to w and 15 separately?
explode() is removing 1 letter, and str_split() doesn't have the option to split the string to an unequal string.
$str = "w15xx837ee";
$letters = preg_replace('/\d/', '', $str);
$numbers = preg_replace('/[^\d]/', '', $str);
echo $letters; // outputs wxxee
echo $numbers; // outputs 15837
You could do something like this to separate strings and numbers
<?php
$str = "w15";
$strarr=str_split($str);
foreach($strarr as $val)
{
if(is_numeric($val))
{
$intarr[]=$val;
}
else
{
$stringarr[]=$val;
}
}
print_r($intarr);
print_r($stringarr);
Output:
Array
(
[0] => 1
[1] => 5
)
Array
(
[0] => w
)
If you want it to be as 15 , you could just implode the $intarr !
Use preg_split() to achieve this:
$arr = preg_split('~(?<=\d)(?=[a-zA-Z])|(?<=[a-zA-Z])(?=\d)~', $str);
Output:
Array
(
[0] => w
[1] => 15
)
For example, the string w15g12z would give the following array:
Array
(
[0] => w
[1] => 15
[2] => g
[3] => 12
[4] => z
)
Demo
Much cleaner:
$result = preg_split("/(?<=\d)(?=\D)|(?<=\D)(?=\d)/",$str);
Essentially, it's kind of like manually implementing \b with a custom set (rather than \w)

Can we do multiple explode statements on one line in PHP? [duplicate]

This question already has answers here:
How to split a string by multiple delimiters in PHP?
(4 answers)
Closed 12 months ago.
Can we do multiple explode() in PHP?
For example, to do this:
foreach(explode(" ",$sms['sms_text']) as $no)
foreach(explode("&",$sms['sms_text']) as $no)
foreach(explode(",",$sms['sms_text']) as $no)
All in one explode like this:
foreach(explode('','&',',',$sms['sms_text']) as $no)
What's the best way to do this? What I want is to split the string on multiple delimiters in one line.
If you're looking to split the string with multiple delimiters, perhaps preg_split would be appropriate.
$parts = preg_split( '/(\s|&|,)/', 'This and&this and,this' );
print_r( $parts );
Which results in:
Array (
[0] => This
[1] => and
[2] => this
[3] => and
[4] => this
)
Here is a great solution I found at PHP.net:
<?php
//$delimiters must be an array.
function multiexplode ($delimiters,$string) {
$ready = str_replace($delimiters, $delimiters[0], $string);
$launch = explode($delimiters[0], $ready);
return $launch;
}
$text = "here is a sample: this text, and this will be exploded. this also | this one too :)";
$exploded = multiexplode(array(",",".","|",":"),$text);
print_r($exploded);
//And output will be like this:
// Array
// (
// [0] => here is a sample
// [1] => this text
// [2] => and this will be exploded
// [3] => this also
// [4] => this one too
// [5] => )
// )
?>
you can use this
function multipleExplode($delimiters = array(), $string = ''){
$mainDelim=$delimiters[count($delimiters)-1]; // dernier
array_pop($delimiters);
foreach($delimiters as $delimiter){
$string= str_replace($delimiter, $mainDelim, $string);
}
$result= explode($mainDelim, $string);
return $result;
}
You could use preg_split() function to stplit a string using a regular expression, like so:
$text = preg_split('/( |,|&)/', $text);
I'd go with strtok(), eg
$delimiter = ' &,';
$token = strtok($sms['sms_text'], $delimiter);
while ($token !== false) {
echo $token . "\n";
$token = strtok($delimiter);
}

Categories