How to read article text file to string? - php

I want PHP read my article text file like this.
sample text file :
OMG! Where is my right hand.
I try to find my right hand but I can't see it.
please tell me how to find it.
Now I have this function code
function getContent($file_path,$path=''){
$file_path = $file_path;
if(file_exists('./'.$file_path)){
$f_read = fopen($path.$file_path,'r');
$rs = "";
while (!feof($f_read)) {
$rs .= fread($f_read, 8192);
}
fclose($f_read);
}
else{
echo $rs = "Not Connect File !";
}
return($rs);
}
after use that code :
OMG! Where is my right hand. I try to find my right hand but I can't see it. please tell me how to find it.
I want to use PHP function read first line to string1 and after first line is string2 like this
$string1 = "OMG! Where is my right hand."
$string2 = "I try to find my right hand but I can't see it.
please tell me how to find it."
Help me please :)

You can use below code for splitting your paragraph into string and also assign the character (like period, comma, etc.) from where do you want the paragraph to split.
preg_split('/[.?!]/',$mystring);
You may refer this link for more information: Explode a paragraph into sentences in PHP
or
http://php.net/manual/en/function.explode.php

You can use $string=#file_get_contents($path_name); $string=#explode("\n",$string); //for get each line.

In order to to read the first line into $string1 and the rest of the file into $string2 ...
Read the first line, as you do above, then call file_get_contents to get the rest.
Use the offset parameter to tell file_get_contents() to start reading after the end of the first line (pass the string length of the first line).

try using explode() function of PHP
function getContent($file_path,$path=''){
$file_path = $file_path;
if(file_exists('./'.$file_path)){
$f_read = fopen($path.$file_path,'r');
$rs = "";
while (!feof($f_read)) {
$rs .= fread($f_read, 8192);
$demo=explode('.', $rs);
}
fclose($f_read);
}
else{
echo $rs = "Not Connect File !";
}
return($demo);//result wiil be stored in $demo array like $demo[0], $demo[1]
}

Related

PHP string comparison to a txt

The $search is a string of variables made from text inputs in a form. I am looking to see if that string is found in a txt file. I think something is wrong with my regex but I am not sure.
An existing entry to the text file would look like this Title%Author%ISBN%Publisher%Year.
My issue is that when I submit the form it goes to a blank page.
elseif ($inquiry=='search') {
$file= fopen("database.txt", "r") or die("File was not found on server");
$search = "/^[$Title."%".$Author."%".$ISBN."%".$Publisher."%".$Year]/i";
//search function
// What to look for
// open and Read from file
$lines = file('database.txt');//array
foreach($lines as $line) {
// Check if the line contains the string we're looking for, and print if it does
if(preg_match($search, $line)) {
echo $line;
} else {
echo "Search not found";
}
}
}
fclose($file);
}
You have to be aware of two things first.
The special $ char in PHP is used to denominate a variable.
When you inject a word with a preceding $ in a double quoted string, this is treated as a variable name and the variable tries to expand itself.
I'm mentioning this because of this line:
$search = "/^[$Title."%".$Author."%".$ISBN."%".$Publisher."%".$Year]/i";
So, my best guess there is that you are trying to use and expand the variable names. So, if that's the case you are ok on your intention.
But be aware you have a missmatched and no closed " after the Title.
Also remember the $ has a special meaning in regular expressions, and they are usually used to try to match the "end of the line".
Note: Your script is probably dying due to a missing " after the Title.

How to grab a word from a page

I was wondering how to grab some text from an external page using PHP.
I think that preg_match() can help but I can't get how to use it.
The text in the page is the following:
dragontail-5.7.2.tgz
and I need to grab only
5.7.2
Thank you for helping.
Check this out:
https://regex101.com/r/cF8mS1/1
/([0-9.]+)/gm
Means "Select all the integer characters since they are more than 1, and include the "." as well, and give me all of them, on multiline too. Thank you."
The last thing to do is to delete the last or first character ".", so:
if (preg_match('/([0-9.]+)/gm', $input, $matches)) {
$result = trim($matches[1], '.');
} else {
$result = null;
}

preg_match and reg expression using alphanumeric, commas, periods, exclamations, etc

I am having one hell of a time coming up with a decent way make this if statement search a file for these codes. I set up the text file to read from as such:
myfile.txt
r)
0Y7
1a6
q.
#g
#(
#a
!P
T[
V}
0,
Here is a brief of what I got going.
$subject = file_get_contents(fvManager_Path . 'myfile.txt');
if ( preg_match('/^[a-zA-Z0-9,]+$/',$result['fmbushels_itemCode'], $subject) ) {
Basically I am trying to search the text file line by line to see if the whole string exists. They are case sensitive as well.
$result['fmbushels_itemCode'] is from a sql query and always returns a code like the above in the text.
I'd appreciate any help on this. If someone knows a better way of doing this or a different command, I'd be willing to give that a shot as well :)
edit:
private function _fvShareBushels() {
$subject = file_get_contents(fvManager_Path . 'myfile.txt');
if (count($vShareArray) > 0) {
$vCntMoves = count($vShareArray);
for ($vI = 0;$vI < $vRunMainLoop;$vI++) {
sell $result['fmbushels_itemCode']);
}
}
}
This is a snippet of a big code. I had to rip most out because of post limitation. The area I could be working with is:
if (count($vShareArray) > 0) {
If I could make this something like:
if (count($vShareArray) > 0 && $result['fmbushels_itemCode'] **is not in** $subject) {
If you want to do line by line, use the file() function.
$f = file(fvManager_Path . 'myfile.txt');
foreach($f AS $line){
// $line is current line at file
}
I'm not to sure if you understand completely how preg_match works. The first parameter is the regular expression pattern, the second is what you want to match the pattern to, and the third is an array of matches. So for every valid pattern matched in the second parameter a new index on the array is created.
I'm not 100% on what you're trying to accomplish. Are you trying to see if the $result['fmbushels_itemCode'] exists in the file?
If the above is the correct case you simply just need to do something like:
$f = file('myfile.txt');
array_map('trim', $f);
if(in_array($result['fmbushels_itemCode'], $f)){
// success
}

PHP in_array() does not find content that is in an array

i have a very simple script that reads out a txt file, puts the content in an array.
Which does perfectly, i can do print_r($array); and it outputs all the data.
My script:
<?php
$file = 'countries.txt';
$countries_output = file_get_contents($file);
$countries_pieces = explode("\n", $countries_output);
if (in_array("Sweden", $countries_pieces)) {
echo "Sweden was found";
}
else
{
echo'NOT FOUND';
}
print_r($countries_pieces);
?>
I don't understand why it doesn't find the value 'Sweden' in my array, when it clearly is in there.
This is the output: https://pastebin.com/z9rC9Qvk
I also print_r the array, so you can see that 'Sweden' is indeed in the array.
Hope someone can help :)
There is most likely new line characters that you're not taking into account. The following is a cleaner solution using file() and should work for you:
$file = 'countries.txt';
$countries_pieces = file($file, FILE_IGNORE_NEW_LINES);
if (in_array("Sweden", $countries_pieces)) {
echo "Sweden was found";
} else {
echo'NOT FOUND';
}
If there are still some issues, a common normalization is to trim() values to remove some left-overs:
$countries_pieces = array_map('trim', $countries_pieces);
But this must not cure all issues.
Is countries.txt from a Windows machine? If so, splitting on '\n' won't work very well since there's also a '\r' for every line.
Your print_r output would seem to indicate that since there seems to be an extra newline between every line of output.

identify and execute php code on a string

I would like to know if it's possible to execute the php code in a string. I mean if I have:
$string = If i say <?php echo 'lala';?> I wanna get "<?php echo 'dada'; ?>";
Does anybody knows how?
[EDIT] It looks like nobody understood. I wanna save a string like
$string = If i say <?php count(array('lala'));?>
in a database and then render it. I can do it using
function render_php($string){
ob_start();
eval('?>' . $string);
$string = ob_get_contents();
ob_end_clean();
return $string;
}
The problem is that I does not reconize php code into "" (quotes) like
I say "<?php echo 'dada'; ?>"
$string = ($test === TRUE) ? 'lala' : 'falala';
There are lots of ways to do what it looks like you're trying to do (if I'm reading what you wrote correctly). The above is a ternary. If the condition evaluates to true then $string will be set to 'lala' else set to 'falala'.
If you're literally asking what you wrote, then use the eval() function. It takes a passed string and executes it as if it were php code. Don't include the <?php ?> tags.
function dropAllTables() {
// drop all tables in db
}
$string = 'dropAllTables();';
eval($string); // will execute the dropAllTables() function
[edit]
You can use the following regular expression to find all the php code:
preg_match_all('/(<\?php )(.+?)( \?>)/', $string, $php_code, PREG_OFFSET_CAPTURE);
$php_code will be an array where $php_code[0] will return an array of all the matches with the code + <?php ?> tags. $php_code[2] will be an array with just the code to execute.
So,
$string = "array has <?php count(array('lala')); ?> 1 member <?php count(array('falala')); ?>";
preg_match_all('/(<\?php )(.+?)( \?>)/', $string, $php_code, PREG_OFFSET_CAPTURE);
echo $php_code[0][0][0]; // <?php count(array('lala')); ?>
echo $php_code[2][0][0]; // count(array('lala'));
This should be helpful for what you want to do.
Looks like you are trying to concatenate. Use the concatenation operator "."
$string = "if i say " . $lala . " I wanna get " . $dada;
or
$string = "if i say {$lala} I wanna get {$dada}.";
That is what I get since your string looks to be a php variable.
EDIT:
<?php ?> is used when you want to tell the PHP interpreter that the code in those brackets should be interpreted as PHP. When working within those PHP brackets you do not need to include them again. So as you would just do this:
// You create a string:
$myString = "This is my string.";
// You decide you want to add something to it.
$myString .= getMyNameFunction(); // not $myString .= <?php getMyNameFunction() ?>;
The string is created, then the results of getMyNameFunction() are appended to it. Now if you declared the $myString variable at the top of your page, and wanted to use it later you would do this:
<span id="myString"><?php echo $myString; ?></span>
This would tell the interpreter to add the contents of the $myString variable between the tags.
Use token_get_all() on the string, then look for a T_OPEN_TAG token, start copying from there, look for a T_CLOSE_TAG token and stop there. The string between the token next to T_OPEN_TAG and until the token right before T_CLOSE_TAG is your PHP code.
This is fast and cannot fail, since it uses PHP's tokenizer to parse the string. You will always find the bits of PHP code inside the string, even if the string contains comments or other strings which might contain ?> or any other related substrings that will confuse regular expressions or a hand-written, slow, pure PHP parser.
I would consider not storing your PHP code blocks in a database and evaluating them using eval. There is usually a better solution. Read about Design Pattern, OOP, Polymorphism.
You could use the eval() function.

Categories