I'd like to explode a string, but have the resulting array have specific strings as keys rather than integers:
ie. if I had a string "Joe Bloggs", Id' like to explode it so that I had an associative array like:
$arr['first_name'] = "Joe";
$arr['last_name'] = "Bloggs";
at the moment, I can do:
$str = "Joe Bloggs";
$arr['first_name'] = explode(" ", $str)[0];
$arr['last_name'] = explode(" ", $str)[1];
which is inefficient, because I have to call explode twice.
Or I can do:
$str = "Joe Bloggs";
$arr = explode(" ", $str);
$arr['first_name'] = $arr[0];
$arr['last_name'] = $arr[1];
but I wonder if there is any more direct method.
Many thanks.
I would use array_combine like so:
$fields = array ( 'first_name', 'last_name' );
$arr = array_combine ( $fields, explode ( " ", $str ) );
EDIT: I would also pick this over using list() since it allows you to add fields should you require without making the list() call unnecessarily long.
You can make use of list PHP Manual (Demo):
$str = "Joe Bloggs";
list($arr['first_name'], $arr['last_name']) = explode(" ", $str);
$arr then is:
Array
(
[last_name] => Bloggs
[first_name] => Joe
)
You cannot do explode(" ", $str)[0] in PHP <= 5.3.
However, you can do this:
list($arr['first_name'], $arr['last_name']) = explode(" ", $str);
Related
I have a string that contains multiple templated variables like this:
$str = "Hello ${first_name} ${last_name}";
How can I do to extract these variables in an array like this :
$array = ['first_name', 'last_name'];
Use single quotes instead of double quotes when describing the string.
$str = 'Hello ${first_name} ${last_name}';
preg_match_all('/{(.*?)}/s', $str, $output_array);
dd($output_array[1]);
Use explode function example given below:
$str = "Hello ${first_name} ${last_name}";
$str_to_array = explode("$",$str);
$array = array();
foreach($str_to_array as $data){
if (str_contains($data, '{')) {
$array[] = str_replace("}","",str_replace("{","",$data));
}
}
print_r($array);
You can use a simple regular expression and use preg_match_all to find all the ocurrences, like this:
<?php
$pattern = '|\${.*?}|';
$subject = 'Hello ${first_name} ${last_name}';
$matches = '';
preg_match_all($pattern, $subject, $matches);
print_r($matches);
?>
Result:
Array
(
[0] => Array
(
[0] => ${first_name}
[1] => ${last_name}
)
)
I have two strings that look like this:
$string1 = "aaaa, bbbb, cccc, dddd, eeee, ffff, gggg";
$string2 = "aaaa, ffff";
I have extracted these strings by employing the function array_intersect in PHP and then imploding the resultant arrays into these two strings.
I would like to have elements in $string2 that appear in $string1 echoed out in bold without removing any element in $string1. For example i would like to have the following result echoed out in HTML:
aaaa, bbbb, cccc, dddd, eeee, ffff, gggg
I have implemented the following solution:
$array1 = explode(',', $string2):
foreach($array1 as $t){
$string1= str_replace($t,'<b>'. $t.'</b>',$string1);
}
echo "$string1";
My solution works but i would like to know if there is a better/efficient/cleaner way of achieving this using PHP?
explode-ing the strings back into arrays, so the longer string can be iterated and checking the short string, with in_array, for any matching items:
$string1 = "aaaa, bbbb, cccc, dddd, eeee, ffff, gggg";
$string2 = "aaaa, ffff";
$array1 = explode(", ", $string1);
$array2 = explode(", ", $string2);
$array3 = [];
foreach ( $array1 as $val ) {
if ( in_array($val, $array2) ) {
array_push($array3, "<strong>$val</strong>");
}
else {
array_push($array3, $val);
}
}
$string3 = implode(", ", $array3);
Try it here: https://onlinephp.io/c/431ec
I have a string of this type:
string(11) "2=OK, 3=OK"
from a text file. But I would like to convert it into an array of keys this type :
array (
[2] => Ok
[3] => Ok
)
I was wondering how we could do that in PHP.
Note:- I normally use explode() and str_split() for the conversions string into array but in this case I don't know how to do it.
use explode(), foreach() along with trim()
<?php
$string = "2=OK, 3=OK" ;
$array = explode(',',$string);
$finalArray = array();
foreach($array as $arr){
$explodedString = explode('=',trim($arr));
$finalArray[$explodedString[0]] = $explodedString[1];
}
print_r($finalArray);
https://3v4l.org/ZsNY8
Explode the string by ',' symbol. You will get an array like ['2=OK', ' 3=OK']
Using foreach trim and explode each element by '=' symbol
You can use default file reading code and traverse it to achieve what you want,
$temp = [];
if ($fh = fopen('demo.txt', 'r')) {
while (!feof($fh)) {
$temp[] = fgets($fh);
}
fclose($fh);
}
array_walk($temp, function($item) use(&$r){ // & to change in address
$r = array_map('trim',explode(',', $item)); // `,` explode
array_walk($r, function(&$item1){
$item1 = explode("=",$item1); // `=` explode
});
});
$r = array_column($r,1,0);
print_r($r);
array_walk — Apply a user supplied function to every member of an array
array_map — Applies the callback to the elements of the given arrays
explode — Split a string by a string
Demo.
You can use preg_match_all along with array_combine, str_word_count
$string = "2=OK, 3=OK" ;
preg_match_all('!\d+!', $string, $matches);
$res = array_combine($matches[0], str_word_count($string, 1));
Output
echo '<pre>';
print_r($res);
Array
(
[2] => OK
[3] => OK
)
LIVE DEMO
I know this question has been answered in here before, but the different functions suggested in the other questions have not been to any help for me - and I´ve tried some few.
I have for example this string with three names that outputs from my database every time it's being loaded:
$string = "Joe Hansen, Carl Clarkson Clinton, Miranda Cobweb Fisher-Caine";
I only want it to output:
$string = "Joe, Carl, Miranda";
I tried this one: click - but it only outputs the first name in some situations and not every time. Is there a easy solution to this one? I also tried explode and implode but did not get that to work either.
Something like this?
<?php
$string = "Joe Hansen, Carl Clarkson Clinton, Miranda Cobweb Fisher-Caine";
$names = explode(",", $string);
$firstNames = array_map(function($name) {
$split = explode(" ", trim($name));
return reset($split);
}, $names);
echo implode(", ", $firstNames);
First you can explode() string with comma , separated. Then go through the loop.
and get first name in the array with substr() and then implode with ,.
$string = "Joe Hansen, Carl Clarkson Clinton, Miranda Cobweb Fisher-Caine";
$names = explode(",", $string);
$firstNames = array();
foreach($names as $name){
$firstNames[] = substr(trim($name), 0, strpos(trim($name), " "));
}
echo implode(", ", $firstNames);
First explode the string on ,, loop through the array, then push the elements in a new array and implode it.
$string = "Joe Hansen, Carl Clarkson Clinton, Miranda Cobweb Fisher-Caine";
$new_string=explode(",",$string);
$slipt_arr=explode(" ",$new_string);
$final_arr=array();
foreach ($new_string as $value)
{
$elements=array_filter(explode(" ",$value));
array_push($final_arr,current($elements));
}
echo implode(", ",$final_arr);
Is it possible to using a regular expression, or otherwise create a function that will convert a string containing the php array of any form, in the real array, which can operate?
For Example:
$str = "array(1, array(2), array('key' => 'value'))";
$arr = stringArrayToArray($str);
Maybe there is already such an implementation of task?
Or do not bother, but simply to use eval()?
$arr = eval("return $str;");
You can try explode() function.
Try it.
<?php
$str = "do you love me";
$arr = explode(' ', $str);
print_r($arr);
?>
You can just replace the array( with a [ and ) with ]
as shown below:
$str = "array(1, array(2), array('key' => 'value'))";
$str = str_replace(" ","",str_replace(",","[",$str));
$str = str_replace(")","",str_replace("array(","[",$str));
echo $str;
$arr = explode("[",$str);
var_dump($arr);
?>
this the best I could get.