I have a code which helps to retrieve line from a text file based on the selected value. I want it to only return a specific part of the string starting at position 166 and ending at 177 instead of the whole line. How can I achieve that, can someone please help me.
Php code:
<?php
$file = 'masterfile.out';
$searchfor = '125302532569';
// the following line prevents the browser from parsing this as HTML.
header('Content-Type: text/plain');
// get the file contents, assuming the file to be readable (and exist)
$contents = file_get_contents($file);
// escape special characters in the query
$pattern = preg_quote($searchfor, '/');
// finalise the regular expression, matching the whole line
$pattern = "/^.*$pattern.*\$/m";
// search, and store all matching occurrences in $matches
if(preg_match_all($pattern, $contents, $matches)){
echo "Found matches:\n";
echo implode("\n", $matches[0]);
}
else{
echo "No matches found";
}
?>
Thank you.
CodePudding user response:
Simply, replace this statement: echo implode("\n", $matches[0]);
with this:
echo substr(implode("\n", $matches[0]),166,11);
CodePudding user response:
You can do with substr()
:
https://www.php.net/manual/en/function.substr.php
$partOfContent = substr($contents, 166, 11);