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>";
Related
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);
?>
the code below works for the first word on each line, but how do I get the first number on each line? please keep in mind that the number can be 1 digit or it can be 20 digits long
<?php
$file = new SplFileObject("/tmp/test.txt", "r");
$data = array();
while(! $file->eof()) {
$data[] = array_shift(($file->fgetcsv("|")));
}
echo implode(",", $data);
?>
This gets the first number in a string:
function getFirstNumber($str){
$strlen = strlen( $str );
$num = "";
for( $i = 0; $i <= $strlen; $i++ ) {
$char = substr($str, $i, 1);
if(!is_numeric( $char)){
if(!empty($num))
return intval($num);
}else $num .= $char;
}
return intval($num);
}
$str = "asdfas1234241234lkj 1l2k3j4 1k2j3412341234";
echo getFirstNumber($str);
Here's a fiddle.
The code you presented, gets the first part, not the first word.
You have to walk through the array using foreach, array_walk, ...
For example:
<?php
$file = new SplFileObject("/tmp/test.txt", "r");
$data = array();
while(! $file->eof()) {
foreach($file->fgetcsv("|") as $part) {
if (is_numeric($part)) { //or any other numeric check you like
$data[] = $part;
break;
}
}
}
echo implode(",", $data);
?>
I have text file
name,name1
willhaveishere1
name,name2
willhaveishere2
name,name3
willhaveishere3
i want read it and return like that
$nn = name1
$ss = willhaveishere1
with my code i get only name1
my code is
$file1 = "file.txt";
$file = file($file1);
$count = count($file);
if($count > 0) {
$i = 1;
foreach($file as $row) {
$n = strstr($row, 'name,');
$cc = array("name,");
$dd = array("");
$nn = str_replace($cc, $dd, $n);
echo $nn;
$i++; } }
This is probably what you need
if($count > 0) {
foreach($file as $row) {
$pos = strpos($row, ',');
if($pos !== false){
echo substr($row, $pos + 1);
$nn[] = substr($row, $pos + 1);
} else {
echo $row;
$ss[] = $row;
}
}
}
EDIT
Yes, just loop through, but make sure both $nn and $ss has same count, which is depending on your file.
Also Note: mysql_* functions has been deprecated, so please use mysqli or PDO instead
$count = count($nn);
for($i=0; $i < $count; $i++){
$sql = "INSERT INTO users(name, line) VALUES('$nn[$i]', '$ss[$i]')"; mysql_query($sql);
}
EDIT 2
try this example:
$file = array(
0 => 'name,name1',
1 => 'willhaveishere1',
2 => 'name,name2',
3 => 'willhaveishere2',
4 => 'name,name3',
5 => 'willhaveishere3'
);
$count = count($file);
if($count > 0) {
foreach($file as $row) {
$pos = strpos($row, ',');
if($pos !== false){
$nn[] = substr($row, $pos + 1);
} else {
$ss[] = $row;
}
}
}
echo '<pre>';
$count = count($nn);
for($i=0; $i < $count; $i++){
$sql = "INSERT INTO users(name, line) VALUES('$nn[$i]', '$ss[$i]');";
echo $sql.PHP_EOL;
}
You can try this straightforward method:
if($fh = fopen("file.txt","r")){
$nameBefore = false;
//loop through every line of your file
while (!feof($fh)){
$line = fgets($fh);
//check if the name was detected in previous line
if ($nameBefore !== false)
{
//you have the set of name and line, do what you want
echo $nameBefore . ': ' . $line . '<br />';
$nameBefore = false;
}
else
{
//see if the line is made of two coma separated segments and the first one is 'name'
//Remember the name for the next line
$parts = explode(',', $line);
if (count($parts) == 2 && $parts[0] == 'name')
$nameBefore = $parts[1];
}
}
fclose($fh);
}
One option is to use strpos to find the first occurrence of the character in the line, and if found remove everything from the line before that position. This way you are left with only the part of the line you are interested in.
Code:
$character = ',';
$fileHandle = fopen('file.txt', 'r');
while (!feof($fileHandle)) {
// Retrieve the line from the file
$line = fgets($fileHandle);
// If the line contains the character
// Remove everything before the character
$charPos = strpos($line, $character);
if ($charPos !== false) {
$line = substr($line, $charPos + 1);
}
// Do something with the remainder of the line
echo $line . PHP_EOL;
}
fclose($fileHandle);
Output:
name1
willhaveishere1
name2
willhaveishere2
name3
willhaveishere3
If you wish to retrieve the following line, simply do another retrieve line call in your loop:
while (!feof($fileHandle)) {
// Retrieve two lines in one loop iteration
$lineOne = fgets($fileHandle);
$lineTwo = fgets($fileHandle);
}
Making sure to only apply the comma replace part on the first line. This can lead to problems though if your data is... inconsistent.
Hope this helps.
I have a script that looks through a file and returns every newline as an array element.
$file = fopen("dict.txt", "r");
$entries = array();
while (!feof($file)) { $entries[] = fgets($file); }
fclose($file);
I also have a script which does some utilities with a $_GET variable.
$word = htmlspecialchars($_GET["user"]);
$letters = $word[0] . $word[1] . $word[2];
What I would like to do now is to echo all elements in the $entries array beginning with $letters.
Any help would be much appreciated.
try
foreach($entries as $entry) {
if (strpos($entry, $letters) === 0) {
echo $entry;
}
}
I am looking to echo comma separated elements of an array e.g:
Element1, Element2, Element3, Element4, Element5, Element6
However, for the purposes of keeping the echoed elements neat, I might need to go to a new line after the each second element of each line e.g
Element1, Element2,
Element3, Element4,
Element5, Element6
As is I am doing:
<?php
$labels = Requisitions::getLabelNames($id);
foreach($labels as $label) {
$labels_array[] = $label['name'];
}
echo implode(' ,', $labels_array);
?>
And obviously getting:
Element1, Element2, Element3, Element4, Element5, Element6
How then do i do a newline after each second element of a line using implode() or otherwise?
<?php
$labels = array('Element1', 'Element2', 'Element3', 'Element4', 'Element5', 'Element6');
# Put them into pairs
$pairs_array = array_chunk($labels, 2);
# Use array_map with custom function
function joinTwoStrings($one_pair) {
return $one_pair[0] . ', ' . $one_pair[1];
}
$pairs_array = array_map('joinTwoStrings', $pairs_array);
echo implode(',' . PHP_EOL, $pairs_array);
You can use foreach to achive it, im pasting code for you which will give you your desired output
<?php
$labels = array("Element1", "Element2", "Element3", "Element4", "Element5","Element6");
$key = 1;
$lastkey = sizeof($labels);
foreach($labels as $value)
{
if($key%2)
{
if($key==$lastkey)
{
echo $value;
}
else
{
echo $value.",</br>";
}
}
else
{
if($key==$lastkey)
{
echo $value."</br>";
}
else
{
echo $value.",</br>";
}
}
$key++;
}
?>
untested, but something like this should work
$i = 1;
foreach($labels as $label) {
echo $label;
// add a comma if the label is not the last
if($i < count($labels)) {
echo ", ";
}
// $i%2 is 0 when $i is even
if($i%2==0) {
echo "<br>"; // or echo "\n";
}
$i++;
}
For the sake of fancy:
$labels_array=array("Element 1","Element 2","Element 3","Element 4","Element 5","Element 6");
echo implode(",\n",array_map(function($i){ // change to ",<br />" for HTML output
return implode(", ",$i);
},array_chunk($labels_array,2)));
Online demo
<?php
$labels = Requisitions::getLabelNames($id);
foreach($labels as $label) {
$labels_array[] = $label['name'];
}
for($i=0;$i<count($labels_array);$i++)
{ echo($labels_array[$i]);
if($i % 2 != 0)
{
echo("\n");
}else{echo(",");}
}
?>
$i = 1;
$str = '';
foreach($labels AS $label)
{
$str += "$label, ";
if ($i % 2 == 0)
{
$str += "\n";
}
$i++;
}
//Remove last 2 chars
$str = substr($str,0,(strlen($str)-2));
Unless you need the array for something else, this just builds the string...
<?php
$labels = Requisitions::getLabelNames($id);
$s='';
$i=0;
$l=count($labels);
foreach($labels as $label){
$s.=$label['name'];
// Append delimeter. Makes sure every second, and the last one, will be a line break
$s.=((++$i%2)&&($l!=$i))?' ,':"\n";
}
echo $s;
?>
If you do need the array for something, create it first and modify above as needed.