I have a ID.txt file that looks like this:
"http://something.net/something-ak/41389_718783565_1214898307_q.jpg"
"http://something.net/something-ak/372142_106502518141813_1189943482_q.jpg"
and so on
I want to use PHP to open the file and remove everything before the first " _ " and everything after the second " _ " so I wind up with this:
718783565
106502518141813
and so on
Thing is I don't really know how to do that.
This is what I have so far:
<?PHP
$file_handle = fopen("ID.txt", "rb");
while (!feof($file_handle) ) {
$line_of_text = fgets($file_handle);
$parts = explode('\n', $line_of_text);
// Remove everything before the first "_" and everything after the last "_".
// echo the line
}
fclose($file_handle);
?>
Can someone help me fille in the blanks?
This is what I would do, although a regex might be shorter or more efficient:
$file_handle = fopen("ID.txt", "rb");
while (!feof($file_handle) )
{
$line_of_text = fgets($file_handle);
$parts = explode("\n", $line_of_text);
foreach ($parts as $str)
{
$str_parts = explode('_', $str); // Split string by _ into an array
array_shift($str_parts); // Remove first element
echo current($str_parts)."\n"; // echo current element and newline
// Same as $str_parts[0]
}
}
fclose($file_handle);
Demo: http://codepad.org/uFbVDtbR
Not a big deal, but $lines might be a better variable name there instead of $parts.
If you do need to write this back to the file, you can do this:
ob_start();
// code used above
$new_content = ob_get_clean();
file_put_contents("ID.txt", $new_content);
Relevant references:
http://php.net/manual/en/function.explode.php
http://www.php.net/manual/en/function.array-shift.php
http://php.net/manual/en/function.current.php
http://php.net/manual/en/function.file-put-contents.php
Just use file in a loop
$content = "";
foreach(file("ID.txt", FILE_SKIP_EMPTY_LINES) as $line){
$parts = explode('_', $line);
$content .= $parts[1] . "\n";
}
file_put_contents("ID.txt", $content);
If you want to achieve this by awk,
awk -F _ '{print $2}' ID.txt
Try this
preg_match('/(.*?)(.+?)(.*)/',$line,$matches);
$matches[2] will give the required string
This should work
<?php
// open files
$file_handle = fopen("ID.txt", "rb");
$new_file_handle = fopen("ID2.txt", "wb");
while (!feof($file_handle) ) {
$str = fgets($file_handle);
$start = strpos($str, '_'); // find first "_"
$end = strpos($str, '_', $start + 1); // find next "_"
$newstr = substr($str, $start + 1, $end - $start - 1) . "\n";
fputs($new_file_handle, $newstr);
}
// close files
fclose($file_handle);
fclose($new_file_handle);
// rename
rename("ID2.txt", "ID.txt");
$TXT = file_get_contents(__DIR__.'/in.txt');
$NewTXT = preg_replace('~^.+/[0-9]+_([0-9]+)_.+?$~mi', '$1', $TXT);
file_put_contents(__DIR__.'/out.txt', $NewTXT);
Just rename the .txt files accordingly.
Related
I have a text file where contains 1 line with this setting:
2222;3333
two values splitted by ;.
How i can edit "splitted[0]" or "splitted[1]" and save the new values on file?
Below is what i have until now:
<?php
$file_handle = fopen("mytext.txt", "rw");
while (!feof($file_handle) )
{
$line_of_text = fgets($file_handle);
$parts = explode("\n", $line_of_text);
foreach ($parts as $str)
{
$str_parts = explode(';', $str); // Split string by ; into an array
array_shift($str_parts); // Remove first element
echo current($str_parts)."\n"; // echo current element and newline
// Same as $str_parts[0]
}
}
fclose($file_handle);
?>
<?php
$file = '2222;3333'; // that is your file
$file = explode(';', $file); // This split your file with delimiter ";"
foreach ($file as $newFile) {
// Do whatever you want
var_dump($newFile);
}
I get trouble on replacing the word into special characters
First, I read the txt file and store each line into $line
and put the special character that I want to change into $table array.
How do I change $line with special character $table array one by one based on the position for example, the txt include three words:
pads
password
qwerty
so the program should show
p#ds
p#d$
p#ssword
p#$sword
p#$$word
p#$$w0rd
qwerty
Now my work just change all special characters into a new word.
but how to change it using foreach / for loop one by one based on the position
My code as follows
<?php
$file = fopen("text.txt", "r");
while(!feof($file)) {
$line = fgets($file);
$line = rtrim ($line);
$table = array(
'a'=>'#', 'o'=>'0', 's'=>'$',
);
$length = strlen($line);
for ($i=0 ; $i<$length ; $i++){
$line = strtr ($line, $table);
echo $line."<br>";
};
}
fclose($file);
?>
This should do the job (haven't tested it):
$char_array = str_split($line);
$replaced = FALSE;
foreach($char_array as $char) {
if(array_key_exists($char, $table)) {
$line = str_replace($char, $table[$char], $line, 1);
echo $line."<br>";
$replaced = TRUE;
}
}
if(!$replaced)
echo $line."<br>";
By setting the count argument of str_replace to 1, you make sure only the current character is replaced and not all of them.
Instead of strtr(), use preg_replace() like this:
for ($i=0 ; $i<$length ; $i++){
if (array_key_exists($line[$i], $table)) {
$line = preg_replace('/' . $line[$i] . '/', $table[$line[$i]], $line, 1);
echo $line."<br>";
}
};
I want to read the text file line by line using php while copying only these values 1.23 , 0.5 , -1.8903, 186 , -0095
I will use strtok() to extract the part of each line I want.
I need help writing the code to iterate through each line.
While you read the file you can explode the file into an array of lines, then split by space and get the first element, like :
$text = "00123123 asdjasdjjdaswd
-32423 asdasda sdsagfgasdf
42 adklsdfkasdfsdf";
$lines = explode(PHP_EOL, $text); # EOL = End of line
foreach($lines as $line){
$array = explode(" ", $line);
echo $value = $array[0];
echo "\n";
}
/* Outputs:
00123123
-32423
42
*/
Alternatively you could write a regex that will get you the contents before the first whitespace per line.
I have used given code:-
$file="test.txt";
$linecount = 0;
$handle = fopen($file, "r");
while(!feof($handle)){
$line = fgets($handle);
$array = explode(" ", $line);
echo $value = $array[0];
echo "\n";
$linecount++;
}
fclose($handle);
I have a text file and in it i want to only read the lines that start with an r then a space.
I have tried strpos but it does not seem to work.
$r="r ";
$file = file_get_contents('cached-consensus', true);
$n = explode("\n", $file);
foreach($n as $line){
$pos= strpos($line,$r);
echo $pos;}
Use this:
$file = file_get_contents('cached-consensus', true);
$n = explode("\n", $file);
foreach($n as $line){
if(0 === strpos($line, "r ")){
// do whatever you want with the line
}
}
This checks that $line starts with 'r '. Currently you're just echoing the position of the string (this should be 0).
How to count specific lines in a text file depending on a particular variable in that line.
For example i need to count the lines of a text file only containing for instance $item1 or $item2 etc.
Sounds like you need something like what grep -c do in the shell, try something like this:
$item1 = 'match me';
$item2 = 'match me too';
// Thanks to #Baba for the suggestion:
$match_count = count(
preg_grep(
'/'.preg_quote($item1).'|'.preg_quote($item2).'/i',
file('somefile_input.txt', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES)
)
);
// does the same without creating a second array with the matches
$match_count = array_reduce(
file('somefile_input.txt', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES),
function($match_count, $line) use ($item1, $item2) {
return
preg_match('/'.preg_quote($item1).'|'.preg_quote($item2).'/i', $line) ?
$match_count + 1 : $match_count;
}
);
The above code sample uses the file() function to read the file into an array (splitted by lines), array_reduce() to iterate that array and preg_match() inside the iteration to see if a line matched (the /i at the end makes it case-insensitive).
You could use a foreach as well too.
This code reads file.php and counts only lines containing '$item1' or '$item2'. The check itself could be finetuned, since you have to add a new stristr() for every word you want to check.
<?php
$file = 'file.php';
$fp = fopen($file, 'r');
$size = filesize($file);
$content = fread($fp, $size);
$lines = preg_split('/\n/', $content);
$count = 0;
foreach($lines as $line) {
if(stristr($line, '$item1') || stristr($line, '$item2')) {
$count++;
}
}
echo $count;
Read your file line by line and use strpos to determine if a line contains a specific string/item.
$handle = fopen ("filename", "r");
$counter = 0;
while (!feof($handle))
{
$line = fgets($handle);
// or $item2, $item3, etc.
$pos = strpos($line, $item);
if ($pos !== false)
{
$counter++
}
}
fclose ($handle);