Merge two strings - php

I have a string stored in my table. It's a number of values separated by pipe:
val 1|val2|val 44
I also have another string, separated by semi-colons that I would like to merge unique values from into the first sting.
abcd; efg; hijklmnop3; val2
So I thought that the easiest way would be to convert them into arrays, merge and keep unique and the implode back into the string.
(my loop) {
$arr1 = array();
$arr2 = array();
$arr1[] = explode(';', $str1);
$arr2[] = explode('|', $str2);
$arr3 = implode("|",array_unique(array_merge($arr1,$arr2)));
}
But when I try to
echo $arr3;
I get
Warning: Array to string conversion
What am I missing here?

Just simplify to following:
$str1 = 'abcd; efg; hijklmnop3; val2';
$str2 = 'val 1|val2|val 44 ';
// explode results an array
$arr1 = array_map('trim', explode(';', $str1));
$arr2 = array_map('trim', explode('|', $str2));
// Implode results a string
$string = implode("|", array_unique(array_merge($arr1, $arr2)));
echo $string;
Results in
abcd|efg|hijklmnop3|val2|val 1|val 44
Note, that explode already returns an array. With the following you add an array to an array, but you just want the array.
$arr1[] = explode(';', $str1); is the same as array_push($arr1, explode(';', $str1));
The unique of your question failed, because you need to trim the spaces.
'val2' !== ' val2' <-- see the space

Related

Is there a way to compare two strings where one is the parent string and the other a child string and make bold similar substrings?

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

How to convert a certain type of string into an array with keys in php?

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

PHP find if numbers contained in a string are present in another string

Hi,
I have one string like this:
4,21
and the other like this:
,4,5,6,14,21,22,
I need to find out if any of the numbers contained in the first string are present in the second string but since each number is separated by a comma Im a little confused. What function should I use?
Thank you.
You could convert each string into arrays.
Try this:
$str1 = "4,21";
$array1 = explode(",", $str1);
$str2 = "4,5,6,14,21,22";
$array2 = explode(",", $str2);
$common = array_intersect($array1, $array2);
echo "Common numbers:<br/>";
echo implode(",", $common);

unique array values

I have string of comma separated values.
1,2,3,4,4,4,4,4,4,4,4,01633,4,4
I need to remove the duplicates, so I though of using
array_unique($str);
However, it returns no results. So I decided to output it to see what I have:
print_r($str);
// returns: 1,2,3,4,4,4,4,4,4,4,4,01633,4,4
I'm a little lost. I checked if it is an array and I got true. Here's how that string is created:
$str = '1,2,3';
foreach ($a as $b) {
$str.= ','.$b;
}
What am I missing here?
$str = explode(',', $str); // create array
$newArray = array_unique($str); // then process
actually, though... just do your array_unique() on $a before the string is created.
$a = array_unique($a);
then...
foreach ($a as $b) { // and so on
Convert to an array, remove the repeat values, convert to string
$str = 'whatever';
$arr = explode( ',', $str );
$newArr = array_unique( $arr );
$newStr = implode( ',', $newArr );
Explode on comma, make unique, glue pieces back together:
$str = implode(',', array_unique(explode(',', $str)));

PHP: Split string into 2D array

I have a string which contains quite a bit of data. I want to split the data into a 2D array. The data in the string is split by a ~ (tilde) for the columns and a : (colon) for the different rows.
An example string could be: "London~10~20~cold:New York~23~53~hot:Madrid~43~12~dry".
Thanks.
$string = "London~10~20~cold:New York~23~53~hot:Madrid~43~12~dry";
$array = explode(':', $string);
foreach($array as &$value) $value = explode('~', $value);
Functional way (PHP 5.3.x needed):
$string = "London~10~20~cold:New York~23~53~hot:Madrid~43~12~dry";
$map = array_map(function($el) {
return explode('~', $el);
}, explode(':', $string));
Another alternative would be:
preg_match_all('/(.*?)~(.*?)~(.*?)~(.*?)(?:$|:)/', $string, $array,
PREG_SET_ORDER);
It's more cumbersome in that you have to predefine the column format. It also returns the complete match in each rows [0]. Otherwise (due to PREG_SET_ORDER) it's in your desired 2d format.
Just posting it here to please and annoy the microoptimizers at the same time. Despite the common Stackoverflow meme, the regex is three times faster than the explode loop.
You can split data in php with explode().
So first you have to split the string, than you have to split your entries again with explode().
$data = explode(':', $string);
$array = array();
foreach($data as $d) {
$d = explode('~', $d);
$array[] = $d; //e.g. $array[0][0] --> London
//$array[$d[0]] = array('temperature' => $d[1], 'dont-know' => $d[2], 'climate' => $d[3]); //e.g. $arra['London'] => array(...)
}
A "functional" style
$array = array_map(function($value) {
return explode('~', $value);
}, explode(':',$string););

Categories