0

i want search string in text file. find result and return after : character.

input is alex text file include this item

alex:+123
david:+1345
john:+1456

output is +123

$input = "alex";
file_get_contents("TextFilePath");

//in this step i don't know what should i do

2 Answers 2

1

Maybe not the best solution, but you can use file and loop on the array. explode each line to see if the needle was present.

function findInAFile($filename, $needle) {
    // read file split on newline
    $lines = file($filename);
    // check each line and return first occurence
    foreach ($lines as $line) {
        $arr = explode($needle, $line, 2);
        if (isset($arr[1])) {
            return $arr[1];
        }
    }
}

echo findInAFile('file.txt', $input.':');
Sign up to request clarification or add additional context in comments.

Comments

0

You can use a regular expression match to locate lines beginning with the given input:

$input = "alex";
$text = file_get_contents("TextFilePath");
if (preg_match('#^' . preg_quote($input) . ':(.*)#m', $text, $match) {
    // Found input
    var_dump($match[1]);
}

5 Comments

It's an output variable that receives the result from preg_match php.net/preg_match
the code only work for alex. when i change input value , output doesnt show.
Are you using multi-line mode m for the regex?
Then add m to the regex as above
Thank you very much jspcal. it work. Can you explain the preg_match code block ? im new in php programming . and i want to know how/where you learn this methods ?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.