I want to search for a string in a txt file and if there is one single match then should return the number from that line Eg. string1 22 string2 432 string3 324 Code (markup): If I will seach for string3 it must return 324 I started with this code $file="myfile.txt"; $Body= fopen( $file, 'r' ); $line=explode("\n", $Body); // takes every line Code (markup): Thank you in advance
Is the number being returned with the string the line number the string is found on or something else?
This was the solution I wrote. <?php $body =file("test.txt"); while (list(, $value) = each($body)) { if( preg_match("/(string[0-9]+) ([0-9]+)/", $value, $matches)) { print "$matches[1] $matches[2] <br>"; } } ?> Code (markup):
I will explain again .. your code display every values I have this in a file blabla 21 blablabla 23 bla 29 blablabla 3 Code (markup): I want to search in this file for bla. If bla is found in this file should return the number 3. If I search for blablabla and is found should return 23 and so on.
It's pretty much the same code, with some tweaking <?php $body =file("test.txt"); $string = "bla"; while (list(, $value) = each($body)) { if( preg_match("/$string ([0-9]+)/", $value, $matches)) { print "$matches[1] $matches[2] <br>"; } } ?> Code (markup):
Thank you for your help .. However is not what I want.. This script return all the numbers on a different line 21 23 29 3 Code (markup): And I want to return only the number from that line where is found $string = "bla";
$content = file_get_contents('file.txt'); $search_text = 'bla'; if(preg_match('%\b'.preg_quote($search_text).'\b\s(\d+)%', $content, $out)) { echo $out[1]; }else{ echo 'No match found'; } PHP: