This question already has answers here:
Explode a string to associative array without using loops? [duplicate]
(10 answers)
Closed 7 months ago.
I have a PHP string separated by characters like this :
$str = "var1,'Hello'|var2,'World'|";
I use explode function and split my string in array like this :
$sub_str = explode("|", $str);
and it returns:
$substr[0] = "var1,'hello'";
$substr[1] = "var2,'world'";
Is there any way to explode $substr in array with this condition:
first part of $substr is array index and second part of $substr is variable?
example :
$new_substr = array();
$new_substr["var1"] = 'hello';
$new_substr["var2"] = 'world';
and when I called my $new_substr it return just result ?
example :
echo $new_substr["var1"];
and return : hello
try this code:
$str = "var1,'Hello'|var2,'World'|";
$sub_str = explode("|", $str);
$array = [];
foreach ($sub_str as $string) {
$data = explode(',', $string);
if(isset($data[0]) && !empty($data[0])){
$array[$data[0]] = $data[1];
}
}
You can do this using preg_match_all to extract the keys and values, then using array_combine to put them together:
$str = "var1,'Hello'|var2,'World'|";
preg_match_all('/(?:^|\|)([^,]+),([^\|]+(?=\||$))/', $str, $matches);
$new_substr = array_combine($matches[1], $matches[2]);
print_r($new_substr);
Output:
Array (
[var1] => 'Hello'
[var2] => 'World'
)
Demo on 3v4l.org
You can do it with explode(), str_replace() functions.
The Steps are simple:
1) Split the string into two segments with |, this will form an array with two elements.
2) Loop over the splitted array.
3) Replace single quotes as not required.
4) Replace the foreach current element with comma (,)
5) Now, we have keys and values separated.
6) Append it to an array.
7) Enjoy!!!
Code:
<?php
$string = "var1,'Hello'|var2,'World'|";
$finalArray = array();
$asArr = explode('|', $string );
$find = ["'",];
$replace = [''];
foreach( $asArr as $val ){
$val = str_replace($find, $replace, $val);
$tmp = explode( ',', $val );
if (! empty($tmp[0]) && ! empty($tmp[1])) {
$finalArray[ $tmp[0] ] = $tmp[1];
}
}
echo '<pre>';print_r($finalArray);echo '</pre>';
Output:
Array
(
[var1] => Hello
[var2] => World
)
See it live:
Try this code:
$str = "var1,'Hello'|var2,'World'|";
$sub_str = explode("|", $str);
$new_str = array();
foreach ( $sub_str as $row ) {
$test_str = explode( ',', $row );
if ( 2 == count( $test_str ) ) {
$new_str[$test_str[0]] = str_replace("'", "", $test_str[1] );
}
}
print $new_str['var1'] . ' ' . $new_str['var2'];
Just exploding your $sub_str with the comma in a loop and replacing single quote from the value to provide the expected result.
Related
I have a variable $var and it contain comma separated value.
$var = 'the_ring,hangover,wonder_woman';
I want to make it like below.
$var = 'The Ring,Hangover,Wonder Woman';
I tried $parts = explode(',', $var); also I tried strpos() and stripos() but not able to figure it out.
What can I do to achieve this?
$var = 'the_ring,hangover,wonder_woman';
$list = explode(',', $var);
$list = array_map( function($name){
return ucwords(str_replace('_',' ', $name));
}, $list);
Returns:
Array
(
[0] => The Ring
[1] => Hangover
[2] => Wonder Woman
)
Imploding:
$imploded = implode(',', $list);
Returns:
'The Ring,Hangover,Wonder Woman'
You can use array_walk to do your replace and uppercase:
$var = 'the_ring,hangover,wonder_woman';
$parts = explode(',', $var);
array_walk($parts, function(&$item){
$item = str_replace('_', ' ', $item);
$item = ucwords($item);
});
$var = implode(',', $parts);
Using str_replace() function click here to explain
like this code
$str= 'the_ring,hangover,wonder_woman';
echo str_replace("_"," ","$str");
This is how you replace _ with white spaces using str_replace() function
$var = 'the_ring,hangover,wonder_woman';
echo str_replace("_"," ",$var);
$var = 'the_ring,hangover,wonder_woman';
$var1 = explode(',' $var);
foreach ($var1 as $key => $value) {
$var1[$key]=str_replace("_"," ",$value);
$var1[$key]=ucwords($var1[$key]);
}
$var = implode(',', $var1);
1.use str_replace to replace something in the string. In your case _ is replaced with space
2.use ucFirst method to capitalize every first character in the strings
$replaced = str_replace('_', ' ', $var);
$changed = ucfirst($replaced);
I have string like this
$string = 'title,id,user(name,email)';
and I want result to be like this
Array
(
[0] => title
[1] => id
[user] => Array
(
[0] => name
[1] => email
)
)
so far I tried with explode function and multiple for loop the code getting ugly and i think there must be better solution by using regular expression like preg_split.
Replace the comma with ### of nested dataset then explode by a comma. Then make an iteration on the array to split nested dataset to an array. Example:
$string = 'user(name,email),office(title),title,id';
$string = preg_replace_callback("|\(([a-z,]+)\)|i", function($s) {
return str_replace(",", "###", $s[0]);
}, $string);
$data = explode(',', $string);
$data = array_reduce($data, function($old, $new) {
preg_match('/(.+)\((.+)\)/', $new, $m);
if(isset($m[1], $m[2]))
{
return $old + [$m[1] => explode('###', $m[2])];
}
return array_merge($old , [$new]);
}, []);
print '<pre>';
print_r($data);
First thanks #janie for enlighten me, I've busied for while and since yesterday I've learnt a bit regular expression and try to modify #janie answer to suite with my need, here are my code.
$string = 'user(name,email),title,id,office(title),user(name,email),title';
$commaBetweenParentheses = "|,(?=[^\(]*\))|";
$string = preg_replace($commaBetweenParentheses, '###', $string);
$array = explode(',', $string);
$stringFollowedByParentheses = '|(.+)\((.+)\)|';
$final = array();
foreach ($array as $value) {
preg_match($stringFollowedByParentheses, $value, $result);
if(!empty($result))
{
$final[$result[1]] = explode('###', $result[2]);
}
if(empty($result) && !in_array($value, $final)){
$final[] = $value;
}
}
echo "<pre>";
print_r($final);
I am doing an assignment on how to take a string of text separated by commas and reverse the individual words and return the words in the same order.
This code does that but it is not returning it as a string for some reason and i do not understand.
<?php
function bassAckwards($input)
{
// YOUR CODE HERE
$commas = substr_count($input, ",");
$NumWords = ($commas + 1);
$words = array($input);
for($x=0;$x<$NumWords;$x++)
{
$answer = array(strrev($words[$x]));
$answer = implode(",",$answer);
print $answer;
}
}
?>
function bassAckwards($str){
$words = explode(',', $str);
$reversedWords = array_map('strrev', $words);
return implode(',', $reversedWords);
}
var_dump(bassAckwards('foo,bar,baz')); // string(11) "oof,rab,zab"
Save yourself some headaches and use the built-it functions.
explode
make 'foo,bar,baz' => array('foo','bar','baz')
array_map & strrev
Execute strrev (string reverse) on every element of the array with array_map and return the [modified] array back.
implode
convert the array back to a csv.
$reversedWords = array();
// Explode by commas
$words = explode(',', $input);
foreach ($word in $words) {
// For each word
// Stack it, reversed, in the new array $reversedWords
$reversedWords[] = strrev($word);
}
// Implode by commas
$output = implode(',', $reversedWords);
print $output;
I am trying to call each string from an array. However, I am using this code to generate the array.
function extract_common_words($string, $stop_words, $max_count = 5) {
$string = preg_replace('/ss+/i', '', $string);
$string = trim($string); // trim the string
$string = preg_replace('/[^a-zA-Z -]/', '', $string); // Only take alphabet characters, but keep the spaces and dashes too…
$string = strtolower($string); // Make it lowercase
preg_match_all('/\b.*?\b/i', $string, $match_words);
$match_words = $match_words[0];
foreach ( $match_words as $key => $item ) {
if ( $item == '' || in_array(strtolower($item), $stop_words) || strlen($item) <= 3 ) {
unset($match_words[$key]);
}
}
$word_count = str_word_count( implode(" ", $match_words) , 1);
$frequency = array_count_values($word_count);
arsort($frequency);
//arsort($word_count_arr);
$keywords = array_slice($frequency,0);
return $keywords;
}
It returns an array which I can't seem to get the STRINGS from. So, I want to essentially take the results, and place them in a list which is an array of strings, with each string being the words, in consecutive order from most common to least common.
You can use the strtok function. Or else you can explode the string by whitespace. I hope that helps :)
I have an function that creates an array of words from a string, counts how often each word occurs and then selects the top 21 words.
Trouble I'm having is I then need to shuffle those 21 words. If I try shuffle() my foreach loop will output the number of occurences rather than the word itself.
Can someone show me how to do this? Here is my existing function:
$rawstring = implode(" ", $testimonials);
$rawstring = filterBadWords($rawstring);
// get the word=>count array
$words = array_count_values(str_word_count($rawstring, 1));
// sort on the value (word count) in descending order
arsort($words);
// get the top frequent words
$top10words = array_slice($words, 0, 21);
shuffle($top10words);
foreach($top10words as $word => $value) {
$class = getClass($value);
echo "" . $word . "";
}
you could use
function shuffle_assoc( $array ) {
$keys = array_keys( $array );
shuffle( $keys );
return array_merge( array_flip( $keys ) , $array );
}
eg:
$top10words = array_slice($words, 0, 21);
$top10words = shuffle_assoc($top10words);
foreach($top10words as $word => $value) {
$class = getClass($value);
echo "" . $word . "";
}