2017-07-17 81 views
0

我有特定的文本存储在文本文件中。如何使用Php仅提取Text-ID的“[email protected]”?从字符串中提取特定文本使用php

下面是示例文本:

[X-PHP-始发脚本:0:acr.php

X:< [email protected]>

MIME-版本: 1.0

Content-Type:text/plain;字符集= US-ASCII;

格式=流入

文本ID:< [email protected]>

日期:星期日,2017年7月2日12时22分12秒0500]

任何帮助赞赏。提前致谢。

+0

尝试使用正则表达式与[preg_match()](http://php.net/manual/en/function.preg-match.php)。学习正则表达式时,https://regex101.com是一个很好的资源。 –

+0

有时文本ID可能有所不同。 – Snappy

+0

它是不同的文本“文本ID”或之后的文本? –

回答

1
  $text = '[X-PHP-Originating-Script: 0:acr.php 

x: <[email protected]> 

MIME-Version: 1.0 

Content-Type: text/plain; charset=US-ASCII; 

Format=flowed 

Text-ID: <[email protected]> 

Date: Sun, 02 Jul 2017 12:22:12 +0500]'; 

     preg_match('/Text\-ID:\s<(.*?)>/s', $text, $ret); 
     var_dump($ret[1]); 
     exit; 
1
与您识别器一样开始

载重线 “文本ID:” 使用strpos,然后使用负载他人信息的PHP从该行

爆炸

preg_match

为当前行,来搜索你想要什么样的下面

0

//正确的文本文件格式:

[X-PHP-Originating-Script: 0:acr.php 
x: <[email protected]> 
MIME-Version: 1.0 
Content-Type: text/plain; charset=US-ASCII; 
Format=flowed 
Text-ID: <[email protected]> 
Date: Sun, 02 Jul 2017 12:22:12 +0500] 

//使用下面的代码,并使用str_replace()函数来得到你想要的结果

$myFile = "abc.txt"; 
$lines = file($myFile);//file in to an array 
$abc = str_replace("Text-ID:","",$lines[5]); 
$abc = str_replace("<","",$abc); 
$abc = str_replace(">","",$abc); 
print_r($abc); 

//第二个选项

$myFile = "abc.txt"; 
$lines = file($myFile);//file in to an array 
preg_match('/Text\-ID:\s<(.*?)>/s', $lines[5], $match); 
print_R($match[1]); 
+0

你的回答没有意义。为什么要更改文件?为什么使用'file()'加载内容(这会给你一个所有行作为元素的数组),你会如何在'preg_match()'上应用?将整个文件作为文本字符串加载并直接执行'preg_match()'是否更简单? –

+0

我告诉他要调整文件。我会应用preg_match()数组,我将从$行中获得。 –

+0

就像我说的,这不是必要的。你可以直接对整个字符串执行preg_match()(没有数组),也不需要先“对齐”。没有额外的积分让代码复杂化,不必要的步骤。 –

0

首先创建一个带有虚拟文件名称的记事本文件。之后,将所有文本放在该文件中。请使用我的脚本从给定的字符串中查找特定的字符串。

一次性

$lines= file('dummy.txt'); // write file name here 
$find_word= ''; 
if(count($lines)>0){ 
    //$lk=array_search('Text-ID',$line); 
    foreach ($lines as $lineNumber => $line) { 
     if (strpos($line, 'Text-ID') !== false) { 
       $start = '<'; 
       $end = '>'; 
       $r = explode($start, $line); 
       if (isset($r[1])){ 
        $r = explode($end, $r[1]); 
        $find_word=$r[0]; 
       } 
     } 
    }    
} 
print_r($find_word); exit; 

对于多时间
,如果你想找到阵列字符串多的时间和存储,然后使用这个脚本。

$lines= file('dummy.txt'); // write file name here 
$find_words= ''; 
if(count($lines)>0){ 
    //$lk=array_search('Text-ID',$line); 
    foreach ($lines as $lineNumber => $line) { 
     if (strpos($line, 'Text-ID') !== false) { 
       $start = '<'; 
       $end = '>'; 
       $r = explode($start, $line); 
       if (isset($r[1])){ 
        $r = explode($end, $r[1]); 
        $find_words[]=$r[0]; 
       } 
     } 
    }    
} 
print_r($find_words); exit; 
相关问题