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);
Related
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.
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 storing some data in my database in a comma based string like this:
value1, value2, value3, value4 etc...
This is the variables for the string:
$data["subscribers"];
I have a function which on users request can remove their value from the string or add it.
This is how I remove it:
/* Remove value from comma seperated string */
function removeFromString($str, $item) {
$parts = explode(',', $str);
while(($i = array_search($item, $parts)) !== false) {
unset($parts[$i]);
}
return implode(',', $parts);
}
$newString = removeFromString($existArr, $userdata["id"]);
So in the above example, I am removing the $userdata['id'] from the string (if it exists).
My problem is.. how can I add a value to the comma based string?
Best performance for me
function addItem($str, $item) {
return ($str != '' ? $str.',' : '').$item;
}
You can use $array[] = $var; simply do:
function addtoString($str, $item) {
$parts = explode(',', $str);
$parts[] = $item;
return implode(',', $parts);
}
$newString = addtoString($existArr, $userdata["id"]);
function addToString($str, $item) {
$parts = explode(',', $str);
array_push($parts, $str);
return implode(',', $parts);
}
$newString = addToString($existArr, $userdata["id"]);
In few words, I am trying to replace all the "?" with the value inside a variable and it doesn't work. Please help.
$string = "? are red ? are blue";
$count = 1;
update_query($string, array($v = 'violets', $r = 'roses'));
function update_query($string, $values){
foreach ( $values as $val ){
str_replace('?', $val, $string, $count);
}
echo $string;
}
The output I am getting is: ? are red ? are blue
Frustrated by people not paying attention, I am compelled to answer the question properly.
str_replace will replace ALL instances of the search string. So after violets, there will be nothing left for roses to replace.
Sadly str_replace does not come with a limit parameter, but preg_replace does. But you can actually do better still with preg_replace_callback, like so:
function update_query($string, $values){
$result = preg_replace_callback('/\?/', function($_) use (&$values) {
return array_shift($values);
}, $string);
echo $string;
}
You forgot to set it equal to your variable.
$string = str_replace('?', $val, $string, $count);
You probably want to capture the return from str_replace in a new string and echo it for each replacement, and pass $count by reference.
foreach ( $values as $val ){
$newString = str_replace('?', $val, $string, &$count);
echo $newString;
}
This is the best and cleanest way to do it
<?php
$string = "? are red ? are blue";
$string = str_replace('?','%s', $string);
$data = array('violets','roses');
$string = vsprintf($string, $data);
echo $string;
Your code edited
$string = "? are red ? are blue";
update_query($string, array('violets','roses'));
function update_query($string, $values){
$string = str_replace('?','%s', $string);
$string = vsprintf($string, $values);
echo $string;
}
Ok guys here is the solution from a combination of some good posts.
$string = "? are red ? are blue";
update_query($string, array($v = 'violets', $r = 'roses'));
function update_query($string, $values){
foreach ( $values as $val ){
$string = preg_replace('/\?/', $val, $string, 1);
}
echo $string;
}
As mentioned, preg_replace will allow limiting the amount of matches to update. Thank you all.
You can solve this in two ways:
1) Substitute the question marks with their respective values. There are a hundred ways one could tackle it, but for something like this I prefer just doing it the old-fashioned way: Find the question marks and replace them with the new values one by one. If the values in $arr contain question marks themselves then they will be ignored.
function update_query($str, array $arr) {
$offset = 0;
foreach ($arr as $newVal) {
$mark = strpos($str, '?', $offset);
if ($mark !== false) {
$str = substr($str, 0, $mark).$newVal.substr($str, $mark+1);
$offset = $mark + (strlen($newVal) - 1);
}
}
return $str;
}
$string = "? are red ? are blue";
$vars = array('violets', 'roses');
echo update_query($string, $vars);
2) Or you can make it easy on yourself and use unique identifiers. This makes your code easier to understand, and more predictable and robust.
function update_query($str, array $arr) {
return strtr($str, $arr);
}
echo update_query(':flower1 are red :flower2 are blue', array(
':flower1' => 'violets',
':flower2' => 'roses',
));
You could even just use strtr(), but wrapping it in a function that you can more easily remember (and which makes sense in your code) will also work.
Oh, and if you are planning on using this for creating an SQL query then you should reconsider. Use your database driver's prepared statements instead.
I have a string that contains elements from array.
$str = '[some][string]';
$array = array();
How can I get the value of $array['some']['string'] using $str?
This will work for any number of keys:
$keys = explode('][', substr($str, 1, -1));
$value = $array;
foreach($keys as $key)
$value = $value[$key];
echo $value
You can do so by using eval, don't know if your comfortable with it:
$array['some']['string'] = 'test';
$str = '[some][string]';
$code = sprintf('return $array%s;', str_replace(array('[',']'), array('[\'', '\']'), $str));
$value = eval($code);
echo $value; # test
However eval is not always the right tool because well, it shows most often that you have a design flaw when you need to use it.
Another example if you need to write access to the array item, you can do the following:
$array['some']['string'] = 'test';
$str = '[some][string]';
$path = explode('][', substr($str, 1, -1));
$value = &$array;
foreach($path as $segment)
{
$value = &$value[$segment];
}
echo $value;
$value = 'changed';
print_r($array);
This is actually the same principle as in Eric's answer but referencing the variable.
// trim the start and end brackets
$str = trim($str, '[]');
// explode the keys into an array
$keys = explode('][', $str);
// reference the array using the stored keys
$value = $array[$keys[0][$keys[1]];
I think regexp should do the trick better:
$array['some']['string'] = 'test';
$str = '[some][string]';
if (preg_match('/\[(?<key1>\w+)\]\[(?<key2>\w+)\]/', $str, $keys))
{
if (isset($array[$keys['key1']][$keys['key2']]))
echo $array[$keys['key1']][$keys['key2']]; // do what you need
}
But I would think twice before dealing with arrays your way :D