Display same word in text file using PHP - php

I have text file as below:
text.txt
lebuzzdesbonsplans.com;hotmail.com;26608;828;3.11
lebuzzdesbonsplans.com;hotmail.fr;24798;876;3.53
friendcorp.fr;yahoo.fr;11343;0;0
friendcorp.fr;free.fr;9856;12;.12
friendcorp.fr;wanadoo.fr;9283;1;.01
messengear.fr;free.fr;9090;11;.12
messengear.fr;laposte.net;8107;2;.02
....................................
....................................
PHP code:
<?php
$PMTA_FILE = file_get_contents("text.txt");
$lineFromText = explode("\n", $PMTA_FILE);
$title = "";
$domain = "";
foreach($lineFromText as $line){
$data = explode(";",$line);
$domain = $data[0];
if (array_key_exists($domain, $domains_seen)){
continue;
}
$domains_seen[$domain] = true;
echo $domain;
echo "<br>";
echo $data[2];
echo "<br>";
}
?>
But the result of this code:
lebuzzdesbonsplans.com
26608
friendcorp.fr
11343
messengear.fr
9090
I do not want the result as above, I need the result as below:
lebuzzdesbonsplans.com
26608
24798
friendcorp.fr
11343
9856
9283
messengear.fr
9090
8107
Anyone know help me to get the solution please,Thanks.

You can use
$lines = array_reduce(file("text.txt", FILE_IGNORE_NEW_LINES), function ($a, $b) {
$b = str_getcsv($b, ";");
$a[$b[0]][] = $b[2];
return $a;
});
foreach($lines as $k => $values)
{
echo $k,PHP_EOL;
echo implode(PHP_EOL, $values);
echo PHP_EOL;
}
Output
lebuzzdesbonsplans.com
26608
24798
friendcorp.fr
11343
9856
9283
messengear.fr
9090
8107

natsort($lineFromText);
foreach($lineFromText as $line){
$data = explode(";",$line);
$domain = $data[0];
if (!array_key_exists($domain, $domains_seen)){
echo $domain;
echo "<br>";
}
echo $data[2];
echo "<br>";
$domains_seen[$domain] = true;
}
Update: sort the lines first - that way all the domains will be collected together,

Related

Wrote 2 functions, don't understand what I did wrong

I've been practicing PHP more and more and am trying to do functions daily to learn from them.
Yesterday I wrote 2 functions but they completely didn't work and I was looking for help as to why!
My code:
<?php
function getFilesAndContent($path)
{
$data[] = $fileData;
$folderContents = new DirectoryIterator($path);
foreach ($folderContents as $fileInfo) {
if ($fileInfo->isDot()) {
continue;
}
$fileData = [
'file_name' => $fileInfo->getBasename(),
];
if ($fileInfo->getExtension()) {
$fileData['contents'] = getFileContents($fileInfo->getPathname());
}
$data = $fileData;
}
return $data;
}
function getFileContents($path)
{
$names = file_get_contents($fileInfo->getPathname());
$names = implode("\n", $names);
sort($names);
$contents = '';
foreach ($names as $name) {
$contents += $name . ' (' . strlen($name) . ')<br>';
}
return $contents;
}
foreach (getFilesAndContent('.') as $data) {
echo $data['file_name'];
echo '<br>';
echo $data['contents'];
echo '<hr>';
}
DISLCAIMER: I really would like to get these 2 functions to work BUT I already have a working alternative(thank you very much!) without any functions, this is meant as a learning opportunity for myself to improve, any help would be greatly appreciated!
You have several problems.
First, $data = $fileData; should be $data[] = $fileData;. Adding [] means that the assignment creates a new element in the array, rather than overwriting the entire variable. And when you initialize the variable at the beginning of getFilesAndContent, it should be $data = [];.
Second, file_get_contents($fileInfo->getPathname()) should be file_get_contents($path). $fileInfo is a variable in getFilesAndContent, not getFileContents.
Third, implode() should be explode(). implode joins an array to create a string, explode() splits up a string into an array.
function getFilesAndContent($path)
{
$data = [];
$folderContents = new DirectoryIterator($path);
foreach ($folderContents as $fileInfo) {
if ($fileInfo->isDot()) {
continue;
}
$fileData = ['file_name' => $fileInfo->getBasename(),];
if ($fileInfo->getExtension()) {
$fileData['contents'] = getFileContents($fileInfo->getPathname());
}
$data[] = $fileData;
}
return $data;
}
function getFileContents($path)
{
$names = file_get_contents($path);
$names = explode("\n", $names);
sort($names);
$contents = '';
foreach ($names as $name) {
$contents += $name . ' (' . strlen($name) . ')<br>';
}
return $contents;
}
foreach (getFilesAndContent('.') as $data) {
echo $data['file_name'];
echo '<br>';
echo $data['contents'];
echo '<hr>';
}

How to use strstr() php

I want to cut text in array but I have no idea to cut this
I try strstr() but it not true.
I try
$ff='';
while($row = mysqli_fetch_array($result,MYSQLI_ASSOC)){
$ff .= $row['fav'] . ",";
}
if( strpos( $ff, "_" )) {
$text = strstr($ff, '_');
echo $text;
}
$ff ='A_0089,A_5677,B_4387,A_B_5566,'
I want output show
0089,5677,4387,B_5566,
Here is one example, using substr() with strpos():
$ff='A_0089,A_5677,B_4387,A_B_5566';
$items = explode(',', $ff);
foreach($items as $item) {
echo substr($item, strpos($item, '_')) . "\n";
}
The above code returns:
_0089
_5677
_4387
_B_5566
You're better off not building a string, but building an array. The way you build the string you have a dangling comma, which you do not want.
$ff = array();
while($row = mysqli_fetch_array($result,MYSQLI_ASSOC)){
$ff[] = $row['fav'];
}
foreach($ff as $item) {
echo substr($item, strpos($item, '_')) . "\n";
}
Based on your desire to keep the commas and create a string:
$ff='A_0089,A_5677,B_4387,A_B_5566,';
$items = explode(',', $ff);
foreach($items as $item) {
$new[] = substr($item, strpos($item, '_'));
}
$newFF = implode(',', $new);
echo $newFF;
returns:
_0089,_5677,_4387,_B_5566,
Probably this is what you are looking for
<?php
function test_alter(&$item1)
{
$pattern = '/^[A-Z]{1}[_]{1}/';
$item1 =preg_replace($pattern,"",$item1);
}
$ff="A_0089,A_5677,B_4387,A_B_5566,";
$nff=explode(",",$ff);
array_walk($nff, 'test_alter');
echo implode(",",$nff);
?>

PHP, Match line, and return value

I have multiple lines like this in a file:
Platform
value: router
Native VLAN
value: 00 01
How can I use PHP to find 'Platform' and return the value 'router'
Currently I am trying the following:
$file = /path/to/file
$contents = file_get_contents($file);
$pattern = preg_quote($searchfor, '/');
$pattern = "/^.*$value.*\$/m";
if(preg_match_all($pattern, $contents, $matches)){
echo "Found Data:\n";
echo implode("\n", $matches[0]);
}
else{
echo "No Data to look over";
}
Heres another simple solution
<?php
$file = 'data.txt';
$contents = file($file, FILE_IGNORE_NEW_LINES);
$find = 'Platform';
if (false !== $key = array_search($find, $contents)) {
echo 'FOUND: '.$find."<br>VALUE: ".$contents[$key+1];
} else {
echo "No match found";
}
?>
returns
Here is a really simple solution with explode.
Hope it helps.
function getValue($needle, $string){
$array = explode("\n", $string);
$i = 0;
$nextIsReturn = false;
foreach ($array as $value) {
if($i%2 == 0){
if($value == $needle){
$nextIsReturn = true;
}
}else{
// It's a value
$line = explode(':', $value);
if($nextIsReturn){
return $line[1];
}
}
$i++;
}
return null;
}
$test = 'Platform
value: router
Native VLAN
value: 00 01 ';
echo getValue('Platform', $test);
If the trailing spaces are a problem for you, you can use trim function.

PHP read txt from specific line to the end

In the following, $mensaxe reads the second line of a .txt file:
function getMessageList(){
$this->messageList = array();
if ($handle = #opendir($this->messageDir)) { while ($file = readdir($handle)) { if (!is_dir($file)) { $this->messageList[] = $file; } } }
rsort($this->messageList);
return $this->messageList;}
function displayGuestbook($page=1){
$list = $this->getMessageList();
$startItem = ($page-1)*$this->itemsPerPage;
if (($startItem + $this->itemsPerPage) > sizeof($list)) $endItem = sizeof($list);
else $endItem = $startItem + $this->itemsPerPage;
for ($i=$startItem;$i<$endItem;$i++){
$value = $list[$i];
$data = file($this->messageDir.DIRECTORY_SEPARATOR.$value);
$fecha = trim($data[0]);
$titulu = trim($data[1]);
$mensaxe = trim($data[2]);
unset ($data['0']);
unset ($data['1']);
unset ($data['2']);
echo "<div id=\"comentariu\">
<div>$fecha</div>
<div>$titulu</div>
<div>$mensaxe</div>
</div>"; }
How can I make it read from the second line to the end?
I hard understand your question but maybe you want this. mensaxe will receive all items of array but 0 and 1
$mensaxe = array_slice($data, 2);
You can trim all the array by array_map function:
$mensaxe = array_map(trim, array_slice($data, 2));
UPDATE
to output $mensaxe as a text, you can make string with instead of former newlines
echo "<div id=\"comentariu\">
<div>$fecha</div>
<div>$titulu</div>
<div>".implode('<br>', $mensaxe)."</div>
</div>"; }
You can use array_slice like so:
$mensaxe = array_slice($data, 2);
// ...
echo "<div>$titulu</div>";
echo "<ul>";
foreach($mensaxe as $value) {
echo "<li>$value</li>";
}
echo "</ul>";

Need to change case of a string - PHP

$variable = "test_company_insurance_llc_chennai_limited_w-8tyu.pdf";
I need to display above the $variable like
Test Company Insurance LLC Chennai Limited W-8TYU.pdf
For that I've done:
$variable = str_replace("_"," ","test_company_insurance_llc_chennai_limited_w-8tyu.pdf");
$test = explode(" ", $variable);
$countof = count($test);
for ($x=0; $x<$countof; $x++) {
if($test[$x] == 'w-8tyu' || $test[$x] == 'llc') {
$test[$x] = strtoupper($test[$x]);
//todo
}
}
I've got stuck in the to-do part.
I will change the specific words to uppercase using strtoupper.
Later, how should I need to merge the array?
Any help will be thankful...
$str_in = "test_company_insurance_llc_chennai_limited_w-8tyu.pdf";
$lst_in = explode("_", $str_in);
$lst_out = array();
foreach ($lst_in as $val) {
switch($val) {
case "llc" : $lst_out[] = strtoupper($val);
break;
case "w-8tyu.pdf" : $lst_temp = explode('.', $val);
$lst_out[] = strtoupper($lst_temp[0]) . "." . $lst_temp[1];
break;
default : $lst_out[] = ucfirst($val);
}
}
$str_out = implode(' ', $lst_out);
echo $str_out;
Not terribly elegant, but perhaps slightly more flexible.
$v = str_replace("_"," ","test_company_insurance_llc_chennai_limited_w-8tyu.pdf");
$acronyms = array('llc', 'w-8tyu');
$ignores = array('pdf');
$v = preg_replace_callback('/(?:[^\._\s]+)/', function ($match) use ($acronyms, $ignores) {
if (in_array($match[0], $ignores)) {
return $match[0];
}
return in_array($match[0], $acronyms) ? strtoupper($match[0]) : ucfirst($match[0]);
}, $v);
echo $v;
The ignores can be removed provided you separate the extension from the initial value.
See the code below. I have printed the output of the code as your expected one. So Run it and reply me...
$variable = str_replace("_"," ","test_company_insurance_llc_chennai_limited_w-8tyu.pdf");
$test = explode(" ", $variable);
$countof = count($test);
for ($x=0; $x<$countof; $x++) {
if($test[$x] == 'llc') {
$test[$x] = strtoupper($test[$x]);
//todo
}elseif($test[$x] == 'w-8tyu.pdf'){
$file=basename($test[$x],'pdf');
$info = new SplFileInfo($test[$x]);
$test[$x] = strtoupper($file).$info->getExtension();
}
else{
$test[$x]=ucfirst($test[$x]);
}
}
echo '<pre>';
print_r($test);
echo '</pre>';
echo $output = implode(" ", $test);

Categories