Php first split then for loop - php

I have a string like this:
$d = 'game, story, animation, video';
And I want to change it to a result like this:
game, story, animation, video
So I think I have to split $d by ',' then use a for loop.
I have tried this:
$d = 'game, story, animation, video';
list($a, $b, $c, $d) = explode(" ,", $d);
But how do I split it if I don't know how many ',' are going to be there, and reach the desired result?

There are many ways this could be accomplished here is one.
by using a foreach loop you should be able to accomplish what you are attempting to do.
You also need to assign you array items correctly, by casting as a string and using the [ ] shorthand or using array()
$d = "game, story, animation, video";
$out = '' ;
foreach(explode(",",$d) as $item){
$out .= "<a href='$item' />$item</a>";
}
echo $out;
and if you need the , between you could use this
$d = "game, story, animation, video";
$out = [] ;
foreach(explode(",",$d) as $item){
$out []= "<a href='$item' />$item</a>";
}
echo implode(",",$out);
read more here
implode
explode
foreach

The key here is to realise that you can break this line into two parts:
list($a, $b, $c, $d) = explode(" ,", $d);
First, it takes the string $d and splits it into an array, let's call it $items:
$items = explode(" ,", $d);
Then the list() construct takes the items from that array and puts them into separate named variables:
list($a, $b, $c, $d) = $items;
If you don't know how many items are going to be in the list, you can just skip the second step, and work with the array, probably using a foreach loop:
foreach ( $items as $item ) {
echo "Doing something with '$item'...";
}

<?php
$in = 'game, story, animation, video';
$out = preg_replace('#([a-z]+)#', '$1', $in);
var_dump($out);
Or:
$tags = explode(',', $in);
$tags = array_map('trim', $tags);
$out = [];
foreach($tags as $tag)
$out[] = '' . $tag . '';
$out = implode(', ', $out);
var_dump($out);
Output for each:
string(112) "game, story, animation, video"

Related

Replacing ',' characters in only odd positions

I need replace ',' characters with regex in php, but only in odd positions
I have:
{"phone","11975365654","name","John Doe","cpf","42076792864"}
I want replace ',' to ':', but only the odd:
{"phone":"11975365654","name":"John Doe","cpf":"42076792864"}
I'm trying this regex:
preg_replace('/,/', ':', $data)
But it get all quotes and no only the odd.
Can you help me?
Make it simple:
preg_replace('/(("[a-z]+"),(".+?"))+/', '$2:$3', $a)
Rather than regex, this just converts the list to an array (using str_getcsv() to cope with the quotes). Then loops every other item in the list, using that item as the key and the next item as the value. This can then be json_encoded() to give the result...
$data = str_getcsv(trim($input, "{}"));
$output = [];
for ( $i=0, $k=count($data); $i < $k; $i+=2) {
$output[$data[$i]] = $data[$i+1];
}
echo json_encode($output);
It is not ideal to use regex for this task. Having said that, if you know that your input can be matched by a simple regex, this should do it :
$str = '{"phone","11975365654","name","John Doe","cpf","42076792864"}';
$result = preg_replace('/,(.*?(?:,|[^,]*$))/ms', ':\\1', $str);
This lenient to some extra characters but it will fail if any string contains commas
Example
Here's an example of using standard PHP functions:
$input = '{"phone","11975365654","name","John Doe","cpf","42076792864"}';
$dataIn = str_getcsv(trim($input, '{}'));
$keys = array_filter($dataIn, function ($key) { return !($key & 1); }, ARRAY_FILTER_USE_KEY);
$values = array_filter($dataIn, function ($key) { return $key & 1; }, ARRAY_FILTER_USE_KEY);
$DataOut = array_combine($keys, $values);
$output = json_encode($DataOut);
echo $output;
This code is a lot longer than using a regex, but it is probably easier to read and maintain in the long run. It can cope with commas in the values.
Another option could be using array_splice and loop while there are still elements in the array:
$str = '{"phone","11975365654","name","John Doe","cpf","42076792864"}';
$data = str_getcsv(trim($str, '{}'));
$result = array();
while(count($data)) {
list($k, $v) = array_splice($data, 0, 2);
$result[$k] = $v;
}
echo json_encode($result);
Output
{"phone":"11975365654","name":"John Doe","cpf":"42076792864"}

How to split array in php with 2 strings?

How to split array with , in 2 parts so that that can be used as 2 strings in php?
I am getting this kind of array you can view image with this list.
I want to split this array to post id and title in separate columns.
<li id="recordsArray_'.$value['id'].','.$value['title'].'"></li>
Give a try with below code if it works for you
$arr = array('1,test1','2,test2','3,test3');
foreach($arr as $ar){
$res = explode(',', $ar);
$id = $res[0];
$title = $res[1];
echo 'id-'.$id;
echo ' title-'.$title;
echo '<br>';
}
If you want to separate array into two string, you can use explode like this short code:
$item = '4,test';
$var = explode(',', $item);
echo $var;
and for loop array, you can use
$array = array(YOUR_ARRAY);
foreach($array as $item){
$var = explode(',', $item);
echo $var;
}
Update 1:
You can use a simple array like below code:
$array = array(4, 'salar');
and use a code like this:
$array = array(4, 'salar');
foreach ($array as $item) {
dump(explode(',', $item));
}

How to perform an action on each imploded value?

I do not have a real use case but am simply wondering if this is possible and how i should do it.
Let's say I have the following array:
$array = array('1234', '5678', '9101', '1121', '3141');
And I would like to implode that.
$string = implode(',', $array);
Let's say I would like to perform an action on the values before they get implodes. For example reversing the string using strrev(). How would I go about this?
Edit
I will try to explain it a little better.
$array = range('a', 'z');
// I know this is not possible
$string = implode(', ', strtoupper($array));
// Desired output : A, B, C, D ...
I am wondering if it can be done using array_map() but ain't good in working with that function.
array_map function should work fine for built-in and "custom" functions(as a first argument of the function):
$array = array('1234', '5678', '9101', '1121', '3141');
$string = implode(', ', array_map("strrev", $array));
print_r($string); // "4321, 8765, 1019, 1211, 1413"
Another approach:
function addSeparator($word, $char = "-") {
$words = str_split($word, 2);
return implode($char, $words);
}
$string = implode(', ', array_map("addSeparator", $array));
print_r($string); // "12-34, 56-78, 91-01, 11-21, 31-41"
Simply do your logic before imploding:
$array = array('1234', '5678', '9101', '1121', '3141');
foreach ($array as &$value) {
$value = strrev($value);
}
$string = implode(',', $array);

Replace string with values from multidimensional array based on a key

I have a variable with multiple number stored as a string:
$string = "1, 2, 3, 5";
and multidimensional array with other stored values:
$ar[1] = array('title#1', 'filename#1');
$ar[2] = array('title#2', 'filename#2');
$ar[3] = array('title#3', 'filename#3');
$ar[4] = array('title#4', 'filename#4');
$ar[5] = array('title#5', 'filename#5');
My goal is to replace number from $string with related tiles from $ar array based on associated array key. For an example above I should to get:
$string = "title#1, title#2, title#3, title#5";
I have tried to loop through $ar and do str_replace on $string, but final value of $string is always latest title from related array.
foreach($ar as $key => $arr){
$newString = str_replace($string,$key,$arr[0]);
}
Any tips how to get this solved?
Thanks
you can do it by str_replace by concat each time or you can do it by explode and concat.
Try Like this:
$string = "1, 2, 3, 5";
$arrFromString = explode(',', $string);
$newString = '';
foreach($ar as $intKey => $arr){
foreach($arrFromString as $intNumber){
if($intKey == $intNumber) {
$newString .= $arr[0].',';
}
}
}
$newString = rtrim($newString,',');
echo $newString;
Output:
title#1,title#2,title#3,title#5
live demo
You can use explode() and implode() functions to get the numbers in $string as an array and to combine the titles into a string respectively:
$res = array();
foreach (explode(", ", $string) as $index) {
array_push($res, $ar[$index][0]);
}
$string = implode(", ", $res);
print_r($string);
will give you
title#1, title#2, title#3, title#5;

Filter array or string(removing some words)

My problem is not very complex but I can't find a solution yet. I have a string:
$temp_string = '20938999038,0.5,83888999289,0.5,98883888778,0.9';
// Meaning syskey, price, syskey, price, syskey, price
I want to remove price and show only syskey.
My desirable result:
'20938999038,83888999289,98883888778'
Thanks in advance.
You can explode it by delimiter
$explode = explode(",", $temp_string);
unset($explode[1], $explode[3], $explode[5]);
Assuming your string always follows this pattern.
You can try:
$string = "20938999038,0.5,83888999289,0.5,98883888778,0.9";
$new = array();
foreach(explode(",", $string) as $k => $v) {
$k % 2 or $new[] = $v;
}
echo implode(",", $new); // 20938999038,83888999289,98883888778

Categories