如何在文本文件中找到一个短语打印出结果PHP?

时间:2014-06-27 09:12:58

标签: php

我使用此代码在.txt文件中找到单词:

<?php
   $lines = file('testXml.txt');
   $what = array ( 'type="abbreviated">', 'type="international">');
    foreach ( $lines as $num => $line ) {
        foreach ( $what as $needle ) {
            $pos = strripos ( $line, $needle );
            if ( $pos !== false ) {
                echo "Line #<b>{$num}</b> : " . htmlspecialchars($line) . "<br />\n";
            }
        }
    } 
?>

,输出为:

Line #1 : <message id="nobill_54050898532262207218"> 
Line #4 : <destination messageid="54050898532262207218"> 
Line #6 : <number type="abbreviated">218</number> 
Line #11 : <number type="international">66830270995</number>

但我只想得到如下输出:

Line #6 : 218
Line #11 : 66830270995

我该怎么办?

完整的文字文件:

<message id="nobill_54050898532262207218"> <sms type="mo"> <retry count="0" max="0"/> <destination messageid="54050898532262207218"> <address> <number type="abbreviated">218</number> </address> </destination> <source> <address> <number type="international">66830270995</number> </address> </source> <ud type="text">,TH</ud> <scts>2013-07-02T02:34:53Z</scts> <service-id></service-id> </sms> <from>nobill</from> <to>203.146.251.229:80</to> </message>

感谢。

2 个答案:

答案 0 :(得分:1)

尝试将htmlspecialchars($line)替换为strip_tags($line)。这应该删除所有HTML开始和结束标记。留下内容。

  

即使内容看起来更像XML,但stip_tags函数应该以相同的方式工作。

更多信息:http://us2.php.net/manual/en/function.strip-tags.php

答案 1 :(得分:0)

使用strip_tags ....

foreach ( $lines as $num => $line ) {
    foreach ( $what as $needle ) {
        $pos = strpos ( $line, $needle );
        if ( $pos !== false ) {
             echo "Line #<b>{$num}</b> : ". strip_tags($line);
        }
    }
 }

或另一种hackish方式......不推荐。

但请注意$ what数组中的完整标记....

$what = array ( '<number type="abbreviated">', '<number type="international">');

foreach ( $lines as $num => $line ) {
    foreach ( $what as $needle ) {
        $pos = strpos ( $line, $needle );
        if ( $pos !== false ) {
            $t = explode("<",str_replace($needle,"",$line));
            echo "Line #<b>{$num}</b> : ". $t[0]."<br>";
        }
    }
}