Saturday, July 10, 2010

how to search string from text file in php

search string from text file in php or find string from text file in php
Note: In this file we store ( write ) all string ( value ) in text ( txt ) file. And searching string start from "name:", "address" and mend with ";".

Note: Save bellow string for search in "test.txt" file.

Hi my name:Kamran; and address:Delhi;. Working as a Software Developer and my area of expertise in PHP and Java/J2EE and I would like to work in software company providing cutting edge PHP and Java base web application.
In this file I am searching string in php name:ahmad; and address:delhi; with php program bellow. searching string from text file in php.

Note: Save bellow file "searchstring.php".
Note: Remove "\" every place from program

<\?php
    $filename = "test.txt";
    $fp = fopen($filename, "r") or die("couldn't open $filename");
    while(!feof($fp))
    {
        $char = fgets($fp);
        $name = strstr($char,'name:');
        $name1 = substr($name, 5);
        $name2 = strpos($name1, ';');

        echo $name3 = substr($name1, 0, $name2);
        echo "<\br>";

        $address = strstr($char,'address:');
        $address1 = substr($address, 8);
        $address2 = strpos($address1, ';');

        echo $address3 = substr($address1, 0, $address2);
        echo "<\br>";
    }
?>