I was trying to get the text starting from css:{(some text...)} up to the ending bracket only, not including the texts below in another text file using php.
test.sample
just a sample text
css:{
"css/test.css",
"css/test2.css"
}
sample:text{
}
I'm using vscode/sublime search and replace tool to test my regex syntax and nothing is wrong, I successfully get the text that I want including all the new lines and spaces inside, but when i tried to apply it on php, the regex that I created doesn't work, it cannot find the text that im looking for.
here is my code:
myphp.php
$file = file_get_contents("src/page/test.sample");
echo $file . "<br>";
if (preg_match_all("/(css\s*\n*:\s*\n*\{\s*\n*)+((.|\n\S)*|(.|\n\s)*)(\n*)(\}\W)$/", $file)) {
echo "Success";
} else {
echo "Failed!";
}
This is my regex that I just created.
(css\s*\n*:\s*\n*{\s*\n*)+((.|\n\S)|(.|\n\s))(\n*)(}\W)$
Please help me, Im open for any suggestion, Im a newbie on regular expression, Im lacking on knowledge about the logic of it.
thanks.
Try this my friend:
<?php
$file = "testfile.php"; // call the file
$f = fopen($file, 'rb'); // open the file
$found = false;
while ($line = fgets($f, 1000)) { // read every line of the file
if ($found) {
echo $line;
continue;
}
if (strpos($line, "css:") !== FALSE) { // if we found the word 'css:' we print everything after that
$found = true;
}
}
Hey guys I found the solution! base on the answer of #alex
Dont really know if I am implementing this right.
Here is my code
$src = "src/page/darwin.al"; //get the source file
$file = fopen($src,"rb"); //I dont really know what 'rb' means, I guess it simply means, 'not a commong text file'?, search for it!
$found = false;
$css = false;
while($line = fgets($file)){ //read every line of text and assign that line of text in a variable $line
if(strpos(preg_replace("/\s*/", "", $line), "css:{") === 0){ //if the current line is == 'css:{' <the thing that Im looking for,
$found = true;
$css = true;
}elseif($css && strpos(preg_replace("/\s*/", "", $line),"}") === 0){ //If we are still inside the css block and found the '{'
echo $line;
break;
}
if ($found) {
echo preg_replace("/\s*/", "", $line); //remove every whitespace!
}
}
fclose($file);//close the file
Related
I am using a simple php translation class and I have about more than 2000 php files which the translation class was implemented and new strings are as well implemented so I need an updated text file with all the translation strings.
I need to get all the translated values from each php file and save it into a text file without any repeated value.
Translation class
<?php $translate->__('Calendar'); ?>
So I need to get Calendar saved into a txt file and this should be done for all the files in all folders.
Everything in between $translate->__(' and ') should be saved.
The below code not working for some reason.
$fn = $_SERVER['DOCUMENT_ROOT']."/apps/test/test2/calendar.php";
$handle = fopen($fn, 'r');
$valid = false;
$search = "\/\\$translate\\-\\>__\\(\\'(.*?)'\\)\/g";
while (($buffer = fgets($handle)) !== false) {
if(preg_match_all($search, $buffer, $m)) {
print $m[1];
} else {
}
}
fclose($handle);
You're extracting strings with this pattern:
/\$translate\-\>__\(\'(.*?)'\)/g
extract all of matched items and save them any where.
Demo and Details : https://regex101.com/r/LzMyJY/1
$fn = $_SERVER['DOCUMENT_ROOT']."/apps/test/test2/calendar.php";
$handle = fopen($fn, 'r');
$valid = false;
$search = "/\\".'$'."translate\\-\\>__\\(\\'(.*?)'\\)/g";
while (($buffer = fgets($handle)) !== false) {
if(preg_match_all($search, $buffer, $m)) {
print $m[1];
} else {
}
}
fclose($handle);
Note:
In use of regex patterns, remember handle backslash \ when putting pattern in ".." (change all \ to \\ in this case)
If using '...' don't change \ with \\ !
So this is my code:
$handle = #fopen("csgo_english.txt", "r"); //read line one by one
$paintkitsStarted = false;
while (!feof($handle)) // Start looping until there is no line anymore.
{
$buffer = fgets($handle, 4096); // Read a line.
$convertedBuffer = $buffer;
echo $convertedBuffer;
if($convertedBuffer == "// Paint Kits "){
$paintkitsStarted = true;
echo "Paintkit Line found! <br>";
}
if($convertedBuffer == "// END CRATE_COMMUNITY_10 "){
$paintkitsStarted = false;
echo "Paintkits ending here! <br>";
}
if($paintkitsStarted == true){
echo $buffer . "<br>";
}
I'm trying to read the .txt-File (which works great) and then comparing a line of it with a string. I already tried casting it to a string using:
$convertedBuffer = "$buffer";
and
$convertedBuffer = (string)$buffer;
as well as
$convertedBuffer = $buffer . "";
I don't know why this isn't working as it should, because I actually took the string I needed by copying it from the output using echo $buffer which should work.
If anyone has Ideas, I would be grateful to hear them :)
Ok, so I still don't know what the problem was. But something probably was wrong with the file, because I just copied the content of the original into a second one and after doing that and trying it with the second one, it worked. Don't ask me why ...
I want the program to print the document contents line by line while not reaching neither the end of file or found the word hi
The problem is when it found the word hi, it prints nothing although it is at position 22. Why not print the previous words how to solve this issue.
My file contain "Php is a special case hi. You will use less memory using the iterative solution. Moreover, function calls in PHP are costly, so it's better to avoid function calls when you can." string.
Here is my code
<?php
$contents = file_get_contents('m.txt');
$search_keyword = 'hi';
// check if word is there
$file=fopen("m.txt","r+");
while(!feof($file)&&strpos($contents, $search_keyword) == FALSE)
{
echo fgets($file)."<br>";
}
?>
change this condition
while(!feof($file)&&strpos($contents, $search_keyword) == FALSE)
to
while(!feof($file)) {
if(strpos($contents, $search_keyword) === FALSE) {
echo fgets($file)."<br>";
} else
break;
}
}
You mean print the file line by line until the word 'hi' is found?
<?php
$search_keyword = 'hi';
$handle = #fopen("m.txt", "r");
if ( $handle )
{
// Read file one line at a time
while ( ($buffer = fgets($handle, 4096)) !== false )
{
echo $buffer . '<br />';
if ( preg_match('/'.$search_keyword.'/i', $subject) )
break;
}
fclose($handle);
}
?>
You can replace the preg_match to strpos if you like.
I've got a problem where I'm trying to read a text file like this:
Joe
Johnson
Linus
Tourvalds
and while parsing it in php, I need to be able to detect the newlines. I'm trying to correctly define $newline. I'm looping through the array of lines in the $file variable.
while($line = next($file))
if($line = $newline)
echo "new line";
The problem is that I can't seem to match the newline character. I know that it is actually showing up in the $file array, because this:
while($line = next($file))
echo $line;
outputs the file verbatim, with newlines and all. I've already tried "\n", " ", and I'm not sure what to try next. A little help?
$file = file("path/to/file.txt");
// Incase you need to call it multiple times ...
function isNewLine($line) {
return !strlen(trim($line));
}
foreach ($file as $line) {
if (isNewLine($line)) {
echo "new line<br/>";
}
}
Maybe something like this would work for you?
while($line = next($file)) {
if(in_array($line, array("\r", "\n", "\r\n"))) {
echo "new line";
}
}
I think this solution may help you guys. This works if you are parsing csv that is generated from Mac or windows. Reading csv with multilines created in Mac, gives problem i.e. you cannot read each line in a loop but all csv data is read as single line.
This problem is solved by following solution:
//My CSV contains only one column
$fileHandle = fopen("test.csv",'r');
$codesArray = array();
count = 0;
while (!feof($fileHandle) ) {
$line = fgetcsv($fileHandle);
if($line[0]!="") {
$data = str_replace("'", "", (nl2br ($line[0])));
$dataArray = explode('<br />' ,$data );
foreach($dataArray as $data) {
$codesArray[] = trim($data);
}
}
}
echo "<pre>";
print_r($codesArray);
I have a txt file that has a change-log.I'm trying to display the new changes only for the current version.
I wrote a function to read the file and check every line if it has the wanted words, if it finds those words it starts to get the content and push it to an array.
I searched to see if there is an example but everyone was talking about how to stop at a specified line, not to start from one.
Here is the code I use:
public function load($theFile, $beginPosition, $doubleCheck) {
// Open file (read-only)
$file = fopen($_SERVER['DOCUMENT_ROOT'] . '/home/' . $theFile, 'r');
// Exit the function if the the file can't be opened
if (!$file) {
return;
}
$changes = Array();
// While not at the End Of File
while (!feof($file)) {
// Read current line only
$line = fgets($file);
// This will check if the current line has the word we look for to start loading
$findBeginning = strpos($line, $beginPosition);
// Double check for the beginning
$beginningCheck = strpos($line, $doubleCheck);
// Once you find the beginning
if ($findBeginning !== false && $beginningCheck !== false) {
// Start storing the data to an array
while (!feof($file)) {
$line = fgets($file);
// Remove space and the first 2 charecters ('-' + one space)
$line = trim(substr($line, 2));
if (!empty($line)) { // Don't add empty lines
array_push($changes, $line);
}
}
}
}
// Close the file to save resourses
fclose($file);
return $changes;
}
It's working currently, but as you can see it's nested loops and that's not good and in case the txt file grows it will take more time!
I'm trying to improve the performance, so does is there any better way to do this ?
much simpler than you think
$found = false;
$changes = array();
foreach(file($fileName) as $line)
if($found)
$changes[] = $line;
else
$found = strpos($line, $whatever) !== false;
That nested loop will not degrade performance, cause it's not really a nested loop in the sense that it is a combinatorially-growing loop over multiple variables. It isn't necessary to write it like that though. Here's another way that avoids it. Try this (pseudocode here):
// skim through the beginning of the file, break upon finding the start
// of the portion I care about.
while (!feof($file)) {
if $line matches beginning marker, break;
}
// now read and process until the endmarker (or eof...)
while (!feof($file)) {
if $line matches endmarker, break;
filter/process/store line here.
}
Also, doublechecking is absolutely not necessary. Why is that there?