explode a:b to a:c php - php

I have 2 files for example
file1.txt
and
file2.txt
file1.txt contains for example following content:
a:b
markus:lanz
peter:heinrichs
lach:schnell
and file2.txt contains for example following content (the 2nd explode of the file1.txt)
b:c
lanz:hallo
heinrichs:gruss
schnell:langsam
so i want to have following output in php:
a:c
markus:hallo
peter:gruss
lach:langsam
how is this possible?
first explode the first and then search or how?
thanks
my current code is following:
<?php
$file1 = 'a:b
markus:lanz
peter:heinrichs
lach:schnell';
$file2 = '
lanz:hallo
heinrichs:gruss
b:c
test:notest
schnell:langsam';
$array = explode(":", $file1);
for($i=0; $i < count($array); $i++) {
$array = explode(":", $file1);
$pattan = $array[$i];
$pattern = '=\n'. $pattan .':(.*)\n=sUm';
$result = preg_match($pattern, $file2, $subpattern);
echo "<br>";
echo $array[$i];
$first = $array[$i];
echo "<br>";
}
$pattern = '=\n'. $first .':(.*)\n=sUm';
$result = preg_match($pattern, $file2, $subpattern);
var_dump($subpattern);
?>
what am i making wrong?

What do you think about this :
$file1="a:b
markus:lanz
peter:heinrichs
lach:schnell";
$file2="b:c
lanz:hallo
heinrichs:gruss
schnell:langsam";
$a1 = explode("\n",$file1);
$a2 = explode("\n",$file2);
if(count($a1) != count($a2)) die("files don't match!");
$final=array();
foreach($a1 as $k=>$line){
$l1 = explode(":",$line);
$l2 = explode(":",$a2[$k]);
$final[]=$l1[0].':'.$l2[1];
}
print_r($final);

I would use the following approach:
// load your two files into arrays using file() and explode each line on ':'
foreach ([1,2] as $n) {
$files[$n] = array_map(function($x){ return explode(':', trim($x));}, file("file$n.txt"));
}
// with file1, fill the output array with 'a' values using 'b' as the key to output
foreach ($files[1] as $ab) {
$output[$ab[1]]['a'] = $ab[0];
}
// with file2, fill the output array with 'c' values, also using 'b' as the key
foreach ($files[2] as $bc) {
$output[$bc[0]]['c'] = $bc[1];
}
// remove any elements that do not have count 2 (i.e. both a and c values)
$output = array_filter($output, function ($x) { return count($x) == 2; });

Related

How to use array_filter in loop

I want to filter the data from the array in a loop. All i want to know is can I use the array_filter inside loop because i am using it and it is not working properly
This is the array which i am getting from DB
Array
(
[0] => Chocolate Manufacturers,C
[1] => ,,,Chocolate Manufacturers,,Chocolate Manufacturers,,Chocolate Manufacturers
[2] =>
)
I am making the array unique by using this code
$num = 2;
for($i=0;$i<count($listing);$i++){
//echo var_export($listing[$i]->cat_title).'<br>';
$listing_cat[$i] = rtrim(ltrim($listing[$i]->cat_title,','),',');
$listing_cat[$i] = explode(',', $listing_cat[$i]);
//$listing_cat[$i] = array_filter(array_keys($listing_cat[$i]), function ($k){ return strlen($k)>=3; });
$listing_cat[$i] = array_filter($listing_cat[$i], function ($sentence){
//divide the each sentence in words
$words = explode(',',$sentence);
$resSentence = [];
//check each words if their length is more then $num
foreach($words as $word){
if(strlen($word) > $num){
$resSentence[] = $word;
}
}
return implode(' ', $resSentence);
});
$listing_cat[$i] = array_unique($listing_cat[$i]);
$listing_cat[$i] = implode(',', $listing_cat[$i]);
$listing_cat[$i] = rtrim(ltrim($listing_cat[$i],','),',');
//$tags['title'][$i] = rtrim(ltrim($listing[$i]->cat_title,','),',');
}
After running this code result is showing like this
Array (
[0] => Chocolate Manufacturers,C
[1] => Chocolate Manufacturers
[2] =>
)
But what i want is to remove the C from the first array i mean to say the unwanted string or string which length will be less than 2 i want to remove that.
Expected Result:
Array (
[0] => Chocolate Manufacturers
[1] => Chocolate Manufacturers
[2] =>
)
i used the below function to remove
$NUM = 2;
$listings[$i] = array_filter($listings[$i], function ($element){
return ($element[$i] > $NUM);
});
But i think because it is in loop it is not working properly. I am placing this code above the array_unique line in loop. All i want is to remove the value which length will be less than 2.
Finally i have achieved my desired answer
$num = 2;
for ($i = 0; $i < count($listing); $i++) {
//$listing_cat[$i] = array_unique($listing[$i]->cat_title);
$listing_cat[$i] = rtrim(ltrim($listing[$i]->cat_title, ','), ',');
$sentence = $listing_cat[$i];
//divide the each sentence in words
$words = explode(',', $sentence);
$resSentence = [];
//check each words if their length is more then $num
foreach ($words as $word) {
if (strlen($word) > $num) {
$resSentence[] = $word;
}
}
$listing_cat[$i] = array_unique($resSentence);
$listing_cat[$i] = implode(',',$listing_cat[$i]);
$listing_cat[$i] = rtrim(ltrim($listing_cat[$i],','),',');
}
echo '<pre>';
print_r($listing_cat);
echo '</pre>';
it is showing perfect result what i want
Array (
[0] => Chocolate Manufacturers
[1] => Chocolate Manufacturers
[2] =>
)
Thanks all for help really appriciated
First of all: I recommend you not to use $listing along with $listings as variable names as it can easily lead to confusion and is not a good readability (especially confusing here on StackOverflow).
Then: You have an error in your code. You are not checking for the length (count) but for the string itself which does resolve in TRUE.
You have:
$NUM = 2;
$listings[$i] = array_filter($listings[$i], function ($element){
return ($element[$i] > $NUM);
}
);
You should have:
$NUM = 2;
$listings[$i] = array_filter($listings[$i], function ($element) use ($NUM) {
return (strlen($element[$i]) >= $NUM);
}
);
You may try the following code:
function arr_filter($arr, $min_length) {
define('STR_MIN_LEN', $min_length);
$arr = array_filter($arr);
$arr_explode = [];
foreach($arr as $value) {
$arr_explode = explode(',', $value);
$arr_explode = array_unique(array_filter($arr_explode));
$arr_explode = array_filter($arr_explode, function($element) {
return strlen($element) >= STR_MIN_LEN;
});
}
return array_values(array_unique($arr_explode));
}
var_dump(arr_filter($arr, 2));
The above code is written as per your requirements. You could try it out and see if it works. This code may not be flexible. You can check it out with various test cases. Hope it works.
EDIT
I assume you have a multidimensional array like:
$arr = array(
array(
'Chocolate Manufacturers,C',
',,,Chocolate Manufacturers,,Chocolate Manufacturers,,Chocolate Manufacturers',
''
),
array(
'Ice Cream Manufacturers,C',
',,,Ice Cream Manufacturers,,Ice Cream Manufacturers,,Ice Cream Manufacturers',
''
)
);
and the code is:
function arr_filter($arr, $min_length) {
define('STR_MIN_LEN', $min_length);
$final_arr = array();
foreach($arr as $value) {
$value = array_filter($value);
$arr_explode = [];
foreach($value as $another_value) {
$arr_explode = explode(',', $another_value);
$arr_explode = array_unique(array_filter($arr_explode));
$arr_explode = array_filter($arr_explode, function($element) {
return strlen($element) >= STR_MIN_LEN;
});
}
$final_arr[] = array_values(array_unique($arr_explode));
}
return $final_arr;
}
var_dump(arr_filter($arr, 2));
I've added this code to make it work with multidimensional array. Hope it works for sure.
EDIT 2
function arr_filter($arr, $min_length) {
define('STR_MIN_LEN', $min_length);
$final_arr = array();
foreach($arr as $value) {
$value = array_filter($value);
$arr_explode_final = [];
foreach($value as $another_value) {
$arr_explode = explode(',', $another_value);
$arr_explode = array_filter($arr_explode, function($element) {
return strlen($element) >= STR_MIN_LEN;
});
// the comma will be added if the string has two different words with comma-separated like `Chocolate Manufacturers, Ice Cream Manufacturers` else comma will be ommited
$arr_explode_final[] = implode(',', array_unique($arr_explode));
}
$final_arr[] = $arr_explode_final;
}
return $final_arr;
}
var_dump(arr_filter($arr, 2));
As you are code say, $listings is contains sentence. If I got your problem properly then, you want to remove smaller from each sentences of the $listings variable.
You can replace your this code:
$NUM = 2;
$listings[$i] = array_filter($listings[$i], function ($element){
return ($element[$i] > $NUM);
});
with the following codeblock:
$num = 2;
$sentence = $listings[$i];
//divide the each sentence in words
$words = explode(',',$sentence);
$resSentence = [];
//check each words if their length is more then $num
foreach($words as $word){
if(strlen($word) > $num){
$resSentence[] = $word;
}
}
$listings[$i] = implode(' ', $resSentence);
Update
I have check out this program below, is it the whole think what you want?
<?php
$listing_cat = ['Chocolate Manufacturers,C', ',,,Chocolate Manufacturers,,Chocolate Manufacturers,,Chocolate Manufacturers', ''];
$num = 2;
for ($i = 0; $i < count($listing_cat); $i++) {
$listing_cat[$i] = rtrim(ltrim($listing_cat[$i], ','), ',');
$sentence = $listing_cat[$i];
//divide the each sentence in words
$words = explode(',', $sentence);
$resSentence = [];
//check each words if their length is more then $num
foreach ($words as $word) {
if (strlen($word) > $num) {
$resSentence[] = $word;
}
}
$listing_cat[$i] = implode($resSentence);
}
var_dump($listing_cat);

Get step step url in url string of PHP

Lets say i have url like this
$a= "http://zz.com/1/2/3/4/5/6/7";
say that url can have many step like 1 ,2 ,3 say something it have up to 3 or sometime up to 7
I want to get url like this from $a
$b="http://zz.com/";
$c="http://zz.com/1/";
$d="http://zz.com/1/2/";
$e="http://zz.com/1/2/3/";
...
...
$k= "http://zz.com/1/2/3/4/5/6/;
Is it possible to do such things in php?
Thank you very much .
I tried to use php url parse and explode but get empty value in beginning and end of array.
Very simple way is to use explode() function.
[EDIT] made it use letters as variables if that was necessary
$a= "http://zz.com/14/2/13/4/5/8/7";
//grab the protocol and addy
$x = explode('//',$a);
$y = explode('/',$x[1]);
$letters = array();
$letters[1] = 'a';
$letters[2] = 'b';
$letters[3] = 'c';
$letters[4] = 'd';
$letters[5] = 'e';
$letters[6] = 'f';
$letters[7] = 'g';
$letters[8] = 'h';
$letters[9] = 'i';
$letters[10] = 'j';
//loop through various steps
for($i = 1; $i<=count($y); $i++)
{
$$letters[$i] = $x[0].'//'.$y[0].'/';
for($k=0; $k<$i; $k++)
{
$$letters[$i] .= $y[$k].'/';
}
}
echo $a."\n";
echo $b."\n";
echo $c."\n";
echo $d."\n";
echo $e."\n";
echo $f."\n";
echo $g."\n";
echo $h."\n";
that will output:
http://zz.com/zz.com/
http://zz.com/zz.com/14/
http://zz.com/zz.com/14/2/
http://zz.com/zz.com/14/2/13/
http://zz.com/zz.com/14/2/13/4/
http://zz.com/zz.com/14/2/13/4/5/
http://zz.com/zz.com/14/2/13/4/5/8/
http://zz.com/zz.com/14/2/13/4/5/8/7/
You can see the code working here: http://sandbox.onlinephpfunctions.com/code/4c0446acaf0fd298fc089b743da5a807529e3e0b
[EDIT: with letters here]http://sandbox.onlinephpfunctions.com/code/bb655992fa81f0005938d86697e91272dc57425a
you can try this code:-
<?php
$a= $_SERVER['REQUEST_URI'];//"http://zz.com/1/2/3";
$url = explode('/',str_replace('http://', '', $a));
$next_num = count($url);
echo $next_url = $a.'/'.$next_num;//wil print :- http://zz.com/1/2/3/4
?>
Yes you can and it is pretty easy and it is good to use build in function called parse_url() which extracts some parts of URL.
$url = "http://zz.com/1/2/3/4/5/6/7";
$pathvars = parse_url($url);
$urls = [];
$glue = '';
$counter = 'a';
foreach ($path as $part) {
$glue .= "$part/";
$urls[$counter++] = sprintf("%s://%s%s", $pathvars['scheme'], substr($pathvars['host'], 0, strlen($pathvars['host']) -1), substr($glue, 0, strlen($glue) - 1));
}
// extract to variables
extract($urls, EXTR_OVERWRITE);
echo $a . PHP_EOL;
echo $b . PHP_EOL;
echo $c . PHP_EOL;
echo $d . PHP_EOL; // etc
print_r($urls); // all array of urls

How to insert a single character between each element in a string to have an array of options

Using PHP, let's say I have this string:
$letters = "abcde";
I would like to add the character "7" between every character, but so it only occurs once. The result should be an array as follows:
$lettersArray = array(
7abcde,
a7bcde,
ab7cde,
abc7de,
abcd7e,
abcde7
);
Note: the length of $letters is dynamic from 1 to 12 characters
I have tried using loops with array_splice and str_split with implode, but I can't quite figure out the right logic.
It is very simple , do like this
echo implode("+", str_split('vimal')); // OUTPUT : v+i+m+a+l
Have a nice day
Try this:
$letters ='abcdefghi';
$lettersArray = array();
for($i=0;$i < strlen($letters)+1; $i++) {
$new = substr($letters, 0, $i);
$new .= '7';
$new .= substr($letters, $i);
$lettersArray[] = $new;
}
print_r($lettersArray);
What this does is take each element of the array, and inserts the letter 7 in an incrementing fashion into the array item.
$split_letters = str_split($letters);
$letters_array = array();
for($i = 0; $i <= count($split_letters); $i++) {
$start_letters = array_slice($split_letters, 0, $i);
$end_letters = array_slice($split_letters, $i);
$letters_array[] = array_merge($start_letters, array(7), $end_letters);
}
After 2 hours (including writing this question) I finally also came up with a solution that is similar to the others posted here. It's posted below, but I prefer other solutions posted here.
$letters = "abcde";
$results = array();
$lettersArray = str_split($letters);
foreach ($lettersArray as $key => $lets) {
$tempArray = $lettersArray;
array_splice($tempArray, $key, 0, "7");
$results[] = implode($tempArray);
}
$results[] = $letters . "7"; //required for the final combination
print_r($results);
Try this
$letters = "abcde";
$character = "7";
$len = strlen($letters);
$lettersArray = array();
for($i=0; $i <= $len; $i++)
{
$temp = "";
$temp = substr($letters, 0, $i) . $character . substr($letters, $i);
$lettersArray[] = $temp;
}
http://codepad.viper-7.com/gFByJb

Modify numbers inside a string PHP

I have a string like this:
$string = "1,4|2,64|3,0|4,18|";
Which is the easiest way to access a number after a comma?
For example, if I have:
$whichOne = 2;
If whichOne is equal to 2, then I want to put 64 in a string, and add a number to it, and then put it back again where it belongs (next to 2,)
Hope you understand!
genesis'es answer with modification
$search_for = 2;
$pairs = explode("|", $string);
foreach ($pairs as $index=>$pair)
{
$numbers = explode(',',$pair);
if ($numbers[0] == $search_for){
//do whatever you want here
//for example:
$numbers[1] += 100; // 100 + 64 = 164
$pairs[index] = implode(',',$numbers); //push them back
break;
}
}
$new_string = implode('|',$pairs);
$numbers = explode("|", $string);
foreach ($numbers as $number)
{
$int[] = intval($number);
}
print_r($int);
$string = "1,4|2,64|3,0|4,18|";
$coordinates = explode('|', $string);
foreach ($coordinates as $v) {
if ($v) {
$ex = explode(',', $v);
$values[$ex[0]] = $ex[1];
}
}
To find the value of say, 2, you can use $whichOne = $values[2];, which is 64
I think it is much better to use the foreach like everyone else has suggested, but you could do it like the below:
$string = "1,4|2,64|3,0|4,18|";
$whichOne = "2";
echo "Starting String: $string <br>";
$pos = strpos($string, $whichOne);
//Accomodates for the number 2 and the comma
$valuepos = substr($string, $pos + 2);
$tempstring = explode("|", $valuepos);
$value = $tempstring[0]; //This will ow be 64
$newValue = $value + 18;
//Ensures you only replace the index of 2, not any other values of 64
$replaceValue = "|".$whichOne.",".$value;
$newValue = "|".$whichOne.",".$newValue;
$string = str_replace($replaceValue, $newValue, $string);
echo "Ending String: $string";
This results in:
Starting String: 1,4|2,64|3,0|4,18|
Ending String: 1,4|2,82|3,0|4,18|
You could run into issues if there is more than one index of 2... this will only work with the first instance of 2.
Hope this helps!
I know this question is already answered, but I did one-line solution (and maybe it's faster, too):
$string = "1,4|2,64|3,0|4,18|";
$whichOne = 2;
$increment = 100;
echo preg_replace("/({$whichOne},)(\d+)/e", "'\\1'.(\\2+$increment)", $string);
Example run in a console:
noice-macbook:~/temp% php 6642400.php
1,4|2,164|3,0|4,18|
See http://us.php.net/manual/en/function.preg-replace.php

Using implode to group information from acquired in a whileloop

I am having the following problem. I have the numbers 1/2/3/4/5/6 and I want to separate them into two groups 1/3/5 and 2/4/6. The selection must take place based on the position. This part works ok. The problem comes when I want to group them again, when I use the implode function; it only sees the last number that was stored. I know it has something to do with me using this notation (I chose this way since the amount of numbers to classify varies every time):
$q++;
$row0 = $row0 + 2;
$row1 = $row1 + 2;
but I can't figure a way to fix it or another way to get the same result. Hopefully someone here can point me in the right direction. I left the complete code below.
<?
$string = "1/2/3/4/5/6";
$splitted = explode("/",$string);
$cnt = count($splitted);
$q=0;
$row0=0;
$row1=1;
while($cnt > 2*$q)
{
$p_row = implode(array($splitted[$row0]));
echo "$p_row <br>";
$i_row = implode(array($splitted[$row1]));
echo "$i_row <br>";
$q++;
$row0 = $row0 + 2;
$row1 = $row1 + 2;
}
$out = "implode(',', $i_row)";
var_dump($out);
?>
I missread the problem it seems. Instead I give this optimization.
$string = "1/2/3/4/5/6";
$splitted = explode("/", $string);
$group = array();
for ($index = 0, $t = count($splitted); $index < $t; ++$index) {
$group[$index & 1][] = $splitted[$index];
}
$oddIndex = $group[0]; //start with index 1
$evenIndex = $group[1]; //start with index 2
echo "odd index: "
. implode('/', $oddIndex)
. "\neven index: "
. implode('/', $evenIndex)
. "\n";
You can split the array into groups using % on loop index. Put each group in separate array. Here is example:
<?php
$string = "1/2/3/4/5/6";
$splitted = explode("/",$string);
$group_odd = array(); ## all odd elements of $splitted come here
$group_even = array(); ## all even elements of $splitted come here
for ($index = 0; $index < count($splitted); ++$index) {
## if number is divided by 2 with rest then it's odd
## but we've started calculation from 0, so we need to add 1
if (($index+1) % 2) {
$group_odd[] = $splitted[$index];
}
else {
$group_even[] = $splitted[$index];
}
}
echo implode('/', $group_odd), "<br />"; ## outputs "1/3/5<br />"
echo implode('/', $group_even), "<br />"; ## outputs "2/4/6<br />"
print_r($group_odd);
print_r($group_even);
?>
Based on their position? So, split based on the evenness/oddness of their index in the array?
Something like this?
<?php
$string = "1/2/3/4/5/6";
list( $evenKeys, $oddKeys ) = array_split_custom( explode( '/', $string ) );
echo '<pre>';
print_r( $evenKeys );
print_r( $oddKeys );
function array_split_custom( array $input )
{
$evens = array();
$odds = array();
foreach ( $input as $index => $value )
{
if ( $index & 1 )
{
$odds[] = $value;
} else {
$evens[] = $value;
}
}
return array( $evens, $odds );
}

Categories