How to explode in foreach loop and implode to one string - php

i need to explode a string in peaces and delete some caracters. Finally i would like to put this string horizontally together.
This is what i try:
$string = "34 asdfadfadf.*****23 vgadfsdfasdf.*****46 asdfasdfadf.";
$arr = explode("*****", $string);
foreach ($arr as $val) {
$val = trim(substr($val, 0, 2));
$arr_neu[] = $val;
}
$array_neu = implode(" ", $arr);
fwrite($flog, "\nstring neu:" . $array_neu);
and this is what i get:
34 asdfadfadf.*****23 vgadfsdfasdf.*****46 asdfasdfadf. 34 23 46
I only need the numbers 34 23 46!
thanks!

Simply with preg_replace function:
$s = '34 asdfadfadf.*****23 vgadfsdfasdf.*****46 asdfasdfadf.';
$result = trim(preg_replace('/[^0-9 ]+/', '', $s));
print_r($result);
The output:
34 23 46
----------
If the string could contain multiple consecutive spaces - change the above approach to the following:
$result = trim(preg_replace('/[^0-9]+/', ' ', $s));

At the end of code you are using wrong variable to implode data
change your code to
$string = "34 asdfadfadf.*****23 vgadfsdfasdf.*****46 asdfasdfadf.";
$arr = explode("*****", $string);
foreach ($arr as $val) {
$val = trim(substr($val, 0, 2));
$arr_neu[] = $val;
}
$array_neu = implode(" ", $arr_neu); // <--------change here. Use $arr_neu
fwrite($flog, "\nstring neu:" . $array_neu);

you just change implode value to $arr_neu instead of $arr
<?php
$string = "34 asdfadfadf.*****23 vgadfsdfasdf.*****46 asdfasdfadf.";
$arr = explode("*****", $string);
foreach ($arr as $val) {
$val = trim(substr($val, 0, 2));
$arr_neu[] = $val;
}
$array_neu = implode(" ", $arr_neu);
fwrite($flog, "\nstring neu:" . $array_neu);

Related

Remove duplicate line with random starts php

I have a file containing data something like this:
randomString-data1
randomString-data2
randomString-data4
randomString-data2
randomString-data2
randomString-data3
randomString-data4
The output I want:
randomString-data1
randomString-data2
randomString-data4
randomString-data3
The length of random string is between 20 to 25 characters. The randomString is not important. The data after it is of relevance only. What could be the best way to remove such duplicates?
All I can think of is the brute force way to explode each line at "-" and compare with all others. But is there a better way?
Note: The random strings are important. But it is okay if any one of the randomString remains from the duplicate entries.
Explode and array flip and then get array keys
$content_array = explode($file_contents);
//Remove duplicate entries
$flipped_array = array_flip($content_array);
file_put_contents('/path/to/file', implode("\n", array_keys($flipped_array));
firstly explode them by '\n' then by '-'
$arr = explode('\n', $str);
$data = array();
foreach($arr as $val)
{
$temp = explode("-", $val);
$data[$temp[1]] = $temp[0];
}
$str = "";
foreach($data as $k => $v)
{
$str .= $v . "-" . $k;
}
i would do it this way
<?php
$file = <<<EOF
randomString-data1
randomString-data2
randomString-data4
randomString-data2
randomString-data2
randomString-data3
randomString-data4
EOF;
$found = [];
foreach (explode("\n", $file) as $line) {
list(, $date) = explode('-', $line);
if (!isset($found[$date])) {
echo "$line<br>";
$found[$date] = true;
}
}
?>

How to re-order array from index value

I'm looking for a way to re-sort a string/array using index value.
Example: string (1,2,3,4,5) change to (1,5,2,3,4)
$string = "1,a,v,v|2,b,v,v|3,c,v,v";
// Convert string to array first...
$sections = explode ('|', $string);
$current_index = "1";
$new_index = "2";
$arrReorder = array();
foreach($sections as $key => $val){
if ($key = $current_index) {
$arrReorder[$new_index] = $val;
}
else {
$arrReorder[$key] = $val;
}
}
$new_string = implode("|", $arrReorder);
echo $new_string;
$new_string should output "1,a,v,v|3,c,v,v|2,b,v,v"
I found a solution for anyone trying to do the same thing:
$string = "1,2,3";
// Convert string to array first...
$sections = explode ('|', $string);
function array_move(&$sections, $oldpos, $newpos) {
if ($oldpos==$newpos) {return;}
array_splice($sections,max($newpos,0),0,array_splice($sections,max($oldpos,0),1));
}
array_move($sections, 0, 2);
print_r($sections);

replace all occurrences after nth occurrence php?

I have this string...
$text = "1|2|1400|34|A|309|Frank|william|This|is|the|line|here|"
How do I replace all the occurrences of | with " " after the 8th occurrence of | from the beginning of the string?
I need it look like this, 1|2|1400|34|A|309|Frank|william|This is the line here
$find = "|";
$replace = " ";
I tried
$text = preg_replace(strrev("/$find/"),strrev($replace),strrev($text),8);
but its not working out so well. If you have an idea please help!
You can use:
$text = '1|2|1400|34|A|309|Frank|william|This|is|the|line|here|';
$repl = preg_replace('/^([^|]*\|){8}(*SKIP)(*F)|\|/', ' ', $text);
//=> 1|2|1400|34|A|309|Frank|william|This is the line here
RegEx Demo
Approach is to match and ignore first 8 occurrences of | using ^([^|]*\|){8}(*SKIP)(*F) and the replace each | by space.
You can use explode()
$text = "1|2|1400|34|A|309|Frank|william|This|is|the|line|here|";
$arr = explode('|', $text);
$result = '';
foreach($arr as $k=>$v){
if($k == 0) $result .= $v;
else $result .= ($k > 7) ? ' '.$v : '|'.$v;
}
echo $result;
You could use the below regex also and replace the matched | with a single space.
$text = '1|2|1400|34|A|309|Frank|william|This|is|the|line|here|';
$repl = preg_replace('~(?:^(?:[^|]*\|){8}|(?<!^)\G)[^|\n]*\K\|~', ' ', $text);
DEMO
<?php
$text = "1|2|1400|34|A|309|Frank|william|This|is|the|line|here|";
$texts = explode( "|", $text );
$new_text = '';
$total_words = count( $texts );
for ( $i = 0; $i < $total_words; $i++)
{
$new_text .= $texts[$i];
if ( $i <= 7 )
$new_text .= "|";
else
$new_text .= " ";
}
echo $new_text;
?>
The way to do that is:
$text = "1|2|1400|34|A|309|Frank|william|This|is|the|line|here|";
$arr = explode('|', $text, 9);
$arr[8] = strtr($arr[8], array('|'=>' '));
$result = implode('|', $arr);
echo $result;
Example without regex:
$text = "1|2|1400|34|A|309|Frank|william|This|is|the|line|here|";
$array = str_replace( '|', ' ', explode( '|', $text, 9 ) );
$text = implode( '|', $array );
str_replace:
If subject is an array, then the search and replace is performed with
every entry of subject, and the return value is an array as well.
explode:
If limit is set and positive, the returned array will contain a
maximum of limit elements with the last element containing the rest of
string.

Split of data in PHP object

In the following code, is it possible to spilt the Object $author where white space occurs ?
<?php
$url="http://search.twitter.com/search.rss?q=laugh";
$twitter_xml = simplexml_load_file($url);
foreach ($twitter_xml->channel->item as $key) {
$a = $key->{"author"};
echo $a;
}
?>
$split = explode(' ', (string) $key->{"author"}));
OR
$split = preg_split('/\s+/', (string) $key->{"author"}));
To split by # just take $split and run in loop
foreach($split as $key => $value) {
$eta = explode('#', $value);
var_dump($eta);
}
To check if string exist use strpos
foreach($split as $key => $value) {
if (strpos($value, '#') !== 0) echo 'found';
}
Use explode:
$array = explode(' ', $key->{"author"});
There is an explode function that can easily accomplish that. So, for example:
$a = $key->{"author"};
$author = explode(" ", $a);
$first_name = $author[0];
$last_name = $author[1];
Hope that helps.
Assuming you merely care to get 2 parts: email, and "friendly name" (cause people have 1 to n number of names).
<?php
$url="http://search.twitter.com/search.rss?q=laugh";
$twitter_xml = simplexml_load_file($url);
foreach ($twitter_xml->channel->item as $key) {
$a = $key->{"author"};
preg_match("/([^ ]*) (.*)/", $a, $matches);
print_r($matches);
echo "\n";
}
?>

PHP grouping by data value

My data variable:
1=icon_arrow.gif,2=icon_arrow.gif,3=icon_arrow.gif
I need it to be grouped by the value after =, so in this case it should look like this:
$out = array('icon_arrow.gif' => '1, 2, 3');
The 'icon_arrow.gif' field need to be unique, and can't repeat.
How it can be done?
Initialize an array:
$array = array();
Explode the input by ,, store results as an array based on a sub-explode of it by =:
foreach(explode(',', $string) as $p)
{
list($i, $n) = explode('=',$p);
$array[$n][] = $i;
}
Implode then the result with ,:
foreach($array as &$v)
$v = implode(', ', $v);
unset($v);
Done.
Just for fun. With no special chars this should also work.
$str="1=icon_arrow.gif,2=icon_arrow.gif,3=icon_arrow.gif,4=x.gif";
$str = str_replace(',', '&', $str);
parse_str($str, $array);
$result = array();
foreach($array as $k=>$v)
$result[$v] = (isset($result[$v]) ? $result[$v] . ", " : "") . $k;

Categories