简体   繁体   English

PHP正则表达式在字符串后回显字符

[英]Php regular expression echo characters after a string

I have a large .txt file, within the .txt file, it contains the numbers 712 and other characters.我有一个很大的 .txt 文件,在 .txt 文件中,它包含数字 712 和其他字符。 example (712iu3 89234) or (712jnksuiosd).例如 (712iu3 89234) 或 (712jnksuiosd)。 The characters after 712 will change, they may have spaces. 712之后的字符会发生变化,可能会有空格。 I have a php script that reads the file line by line.我有一个 php 脚本,可以逐行读取文件。 I am trying to echo all characters after 712 If there are spaces I'd like to remove the spaces.我正在尝试回显 712 之后的所有字符 如果有空格我想删除空格。 I only need the first 20 characters excluding the spaces.我只需要不包括空格的前 20 个字符。 So far I've tried到目前为止我已经尝试过

$file = new SplFileObject("1.txt");

// Loop until we reach the end of the file.
while (!$file->eof()) {
// Echo one line from the file.
echo $file->fgets();
}

// Unset the file to call __destruct(), closing the file handle.
$file = null;

try using the code below尝试使用下面的代码

<?php 
$file = new SplFileObject("test.txt");

// Loop until we reach the end of the file.
while (!$file->eof()) {
    $newString = str_replace(' ', '', $file->fgets());
if (strpos($newString, '712') !== false) {
    $strWith712 = substr($newString, 0, 20);
    $post = strripos($strWith712, '712');
    $str =  substr ($strWith712, $post );
    echo $str;

}

}

$file = null;
?>

this replaces the white spaces and then searches for the string with the number '712' if a string is found then the letters after the number are printed这将替换空格,然后搜索带有数字“712”的字符串,如果找到字符串,则打印数字后面的字母
the strripos function is used to check the postiton of the string in a sentence from the last. strripos函数用于检查字符串在最后一个句子中的位置。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM