php - 如何使用Php从具有特定开始和结束位置的字符串中提取数据?

标签 php

我有一个代码,它有助于根据选定的值从文本文件中检索行。我希望它只返回从位置 166 开始到 177 结束的字符串的特定部分,而不是整行。我怎样才能做到这一点,有人可以帮助我。
代码:

<?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";
}
?>
谢谢你。

最佳答案

简单地,替换这条语句:echo implode("\n", $matches[0]);有了这个:

echo substr(implode("\n", $matches[0]),166,11);

关于php - 如何使用Php从具有特定开始和结束位置的字符串中提取数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70234567/

相关文章:

php - 如何在SQLite中搜索多个值?

php - MySQL连接 'asking for reconnection'

php - 是否可以使用 JS 显示已由 php mysql 填充的新下拉列表?

php - XML 作为数据库

php - 如何使用 SQL 或 PHP 从 mySQL 导出它?

php - 从字符串中删除非ASCII字符

当 php-fpm 返回 500 时,Nginx 返回 502 错误

php - 在 Laravel 5.2 中为所有 Eloquent 模型添加全局方法

javascript - 基于先前选择的下拉列表根本不填充

php - 在服务器上处理需要很长时间的 AJAX 文件的最佳流程