Searching for a substring in text in PHP

In general, I wrote a function that takes a random string from a file:

  $h = fopen('r','file.txt');
  $str = Array();
  while (!EOF)
    $str[] = fgets($h);
  echo $str[rand(0,count($str))];

Here, any random string is taken, but if the file is large, there are 2.3 GB, of course, it will be bad. What is the best way to fix it so that memory is not clogged even with large file sizes?
Here is what I read about memory_limit:

This directive sets the maximum
the amount of memory in bytes that
script is allowed. This
helps to prevent the situation
which poorly written script
eats up all available server memory.
To remove restrictions,
set the value of this directive to

But I don’t understand how to apply it.

And one more question. There is such a function as searching for a string or text using regular expressions. I wrote a script, but it looks for how, that is, if you need to find the string " "in the text, and in the text it will be broken by a hyphen, or have a comma, the script will find only the complete similarity. What function to use or how to change to find a string, a word that does not have a complete match.

    die("Text -$stroka- detected");
  else {    
    echo "Text -$stroka- not detected";
  if (isset($_SERVER['HTTP_REFERER']))
    echo '<a style="margin-right:20px;"

Help, a newbie, please fix it.

Answer 1, authority 100%

About the file. You must first calculate the carries.

$h = fopen('r','file.txt');
$str = Array();
//while (!EOF) // <-    
$linesCnt = 0;
while (!feof($h))
$linesCnt ++;
//,       $linesCnt.
$randLineCnt = rand(0, $linesCnt - 1);
rewind($h); //     (     );
for($i=0; $i < $randLineCnt; $i++) fgets($h);
$randLine = fgets($h);
// .    $randLine     .      2 ,     

About the second one:

regular expressions. I wrote a script, but it looks for how, that is, if you need to find the string “Hi, how are you” in the text …

You must select some mask (i.e., some part of the text must be stable) and use this mask to compose a regular expression.

For example, we want to highlight a part of a sentence that starts with hi and ends with you.

there is text:

"hi, how are
you ?"

regex will be something like this:


Here we applied the /s modifier, which means that in . also includes line breaks

in general something like this

PS: this MarkDown doesn’t listen to me 🙁

Answer 2

Of course, the idea is so-so, but still: if the lines in a 2.3 GB file are approximately the same length, you can first get a random line number, and then rewind the file using fseek to approximately the same line.