Replace string with values from multidimensional array based on a key - php

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;

Related

Saving values from a variable to an array

I have a long string variable that contains coordinates
I want to keep each coordinate in a separate cell in the array according to Lat and Lon..
For example. The following string:
string = "(33.110029967689556, 35.60865999564635), (33.093492845160036, 35.63955904349791), (33.0916232355565, 35.602995170206896)";
I want this:
arrayX[0] = "33.110029967689556";
arrayX[1] = "33.093492845160036";
arrayX[2] = "33.0916232355565";
arrayY[0] = "35.60865999564635";
arrayY[1] = "35.63955904349791";
arrayY[2] = "35.602995170206896";
Does anyone have an idea ?
Thanks
Use substr to modify sub string, it allow you to do that with a little line of code.
$array_temp = explode('),', $string);
$arrayX = [];
$arrayY = [];
foreach($array_temp as $at)
{
$at = substr($at, 1);
list($arrayX[], $arrayY[]) = explode(',', $at);
}
print_r($arrayX);
print_r($arrayY);
The simplest way is probably to use a regex to match each tuple:
Each number is a combination of digits and .: the regex [\d\.]+ matches that;
Each coordinate has the following format: (, number, ,, space, number,). The regex is \([\d\.]+,\s*[\d\.]+\).
Then you can capture each number by using parenthesis: \(([\d\.]+),\s*([\d\.]+)\). This will produce to capturing groups: the first will contain the X coordinate and the second the Y.
This regex can be used with the method preg_match_all.
<?php
$string = '(33.110029967689556, 35.60865999564635), (33.093492845160036, 35.63955904349791), (33.0916232355565, 35.602995170206896)';
preg_match_all('/\(([\d\.]+)\s*,\s*([\d\.]+)\)/', $string, $matches);
$arrayX = $matches['1'];
$arrayY = $matches['2'];
var_dump($arrayX);
var_dump($arrayY);
For a live example see http://sandbox.onlinephpfunctions.com/code/082e8454486dc568a6557058fef68d6f10c8dbd0
My suggestion, working example here: https://3v4l.org/W99Uu
$string = "(33.110029967689556, 35.60865999564635), (33.093492845160036, 35.63955904349791), (33.0916232355565, 35.602995170206896)";
// Split by each X/Y pair
$array = explode("), ", $string);
// Init result arrays
$arrayX = array();
$arrayY = array();
foreach($array as $pair) {
// Remove parentheses
$pair = str_replace('(', '', $pair);
$pair = str_replace(')', '', $pair);
// Split into two strings
$arrPair = explode(", ", $pair);
// Add the strings to the result arrays
$arrayX[] = $arrPair[0];
$arrayY[] = $arrPair[1];
}
You need first to split the string into an array. Then you clean the value to get only the numbers. Finally, you put the new value into the new array.
<?php
$string = "(33.110029967689556, 35.60865999564635), (33.093492845160036, 35.63955904349791), (33.0916232355565, 35.602995170206896)";
$loca = explode(", ", $string);
$arr_x = array();
$arr_y = array();
$i = 1;
foreach($loca as $index => $value){
$i++;
if ($i % 2 == 0) {
$arr_x[] = preg_replace('/[^0-9.]/', '', $value);
}else{
$arr_y[] = preg_replace('/[^0-9.]/', '', $value);
}
}
print_r($arr_x);
print_r($arr_y);
You can test it here :
http://sandbox.onlinephpfunctions.com/code/4bf04e7aabeba15ecfa114d8951eb771610a43a4

Pass comma separated key string and get value of array according to key in PHP

I am trying to get value from array and pass only comma separated key string and get same output without. Is it possible without using foreach statement. Please suggest me.
<?php
$str = "1,2,3";
$array = array("1"=>"apple", "2"=>"banana", "3"=>"orange");
$keyarray = explode(",",$str);
$valArr = array();
foreach($keyarray as $key){
$valArr[] = $array[$key];
}
echo $valStr = implode(",", $valArr);
?>
Output : apple,banana,orange
Use array_intersect_key
$str = "1,2,3";
$array = array("1"=>"apple", "2"=>"banana", "3"=>"orange");
$keyarray = explode(",",$str);
echo implode(",", array_intersect_key($array, array_flip($keyarray)));
https://3v4l.org/gmcON
One liner:
echo implode(",", array_intersect_key($array, array_flip(explode(",",$str))));
A mess to read but a comment above can explain what it does.
It means you don't need the $keyarray
Suggestion : Use separate row for each value, to better operation. Although you have created right code to get from Comma sparate key to Value from array, but If you need it without any loop, PHP has some inbuilt functions like array_insersect , array_flip to same output
$str = "1,2";
$arr1 = ["1"=>"test1","2"=>"test2","3"=>"test3"];
$arr2 = explode(",",$str);
echo implode(", ",array_flip(array_intersect(array_flip($arr1),$arr2)));
Live demo
you can try using array_filter:
$str = "1,2,3";
$array = array("1"=>"apple", "2"=>"banana", "3"=>"orange");
$keyarray = explode(",",$str);
$filtered = array_filter($array, function($v,$k) use($keyarray){
return in_array($k, $keyarray);
},ARRAY_FILTER_USE_BOTH);
print_r($filtered);
OUTPUT
Array
(
[1] => apple
[2] => banana
[3] => orange
)
Another way could be using array_map():
echo $valStr = implode(",", array_map(function ($i) use ($array) { return $array[$i]; }, explode(",", $str)));
Read it from bottom to top:
echo $valStr = implode( // 3. glue values
",",
array_map( // 2. replace integers by fruits
function ($i) use ($array) {
return $array[$i];
},
explode(",", $str) // 1. Split values
)
);

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);

LIKE to search for first three characters of each comma separated value

In a string,
$string_example = "cats, dogs, horses"
I'd like to get
$string_truncated = "cat, dog, hor"
i.e. getting the first three characters of each comma separated value
Later, I will use this in an SQL LIKE statement to restrict search results that match at least the first three characters given (I can't do FULL TEXT because I want to keep my foreign key constraints and can't give up my DB engine)
$string_example = "cats, dogs, horses";
$arr = explode(',',$string_example);
$newArr = array();
foreach($arr as $val){
if($val != ''){
$newArr[] = substr(trim($val),0,3);
}
}
$newStr = implode(', ',$newArr);
echo $newStr;
You can do:
<?php
$string_example = "cats, dogs, horses";
$arr = explode(",", $string_example);
$newArr = array();
foreach($arr as $value) $newArr[] = substr(trim($value), 0, 3);
$newString = implode($newArr,", ");
echo $newString;
?>
Output:
cat, dog, hor
Using array_map, substr, explode and implode:
$string_example = "cats, dogs, horses"
$truncated_ary = array_map(
function($search_string){
return substr($search_string, 0, 3)
},
explode(',', $string_example)
);
$string_truncated = implode(',', $truncated_ary);
$string_example = "cats, dogs, horses";
$words = explode(',',$string_example);
$result = array();
foreach($words as $val){
if($val != ''){
$result[] = substr(trim($val),0,3);
}
}
$newStr = implode(', ',$result);
echo $newStr;

getting all the values in an array except the last one

I have this right now :
$s = preg_split('/\s+/', $q);
$k = end($s);
What I want now is to get all the values in the array $k[] except the last one, and join them in a new string. So basically if the array was :
0 => Hello
1 => World
2 => text
I would get Hello World
Use array_slice and implode:
$k = array( "Hello", "World", "text" );
$sliced = array_slice($k, 0, -1); // array ( "Hello", "World" )
$string = implode(" ", $sliced); // "Hello World";
If you can modify the array:
array_pop($k);
$string = join(' ', $k);
array_pop() pops and returns the last value of the array, shortening the array by one element. If array is empty (or is not an array), NULL will be returned.
Source
Use array_slice($array) to get a subset of any array.
For everything without the last item I believe it is
$return = array_slice($array, 0, count($array)-1, true);
Testcase http://codepad.org/fyHHX5Us
Something like this:
<?php
$array = array('Hello', 'World', 'text');
$new_array = array_slice($array,0,-1);
echo implode(' ',$new_array);
?>
Example

Categories