1

Simply in php we could replace a string by other string such as using a particular function, str_replace (), etc

Suppose I have a file.txt contains

text1
text2
text3
...
text n

and i have a variable $text like

$text = "I want to get text1 and text2";

How to get the strings (text1 and text2) based on the available strings in file.txt?

I want to have a new variable say ($new) which contains strings of $text that it fits on the string file.txt

So i have $new="text1 text2";

I still confused, how to adjust two text.

Any help wouldbe appreciated. Thanks.

3
  • 1
    I would get contents from file into array, explode text at space and loop and compare both arrays. If there's a match push it to a new array. Finally implode the result with spaces to get your final string. Commented May 19, 2013 at 23:35
  • Your question is a bit complicated, do you want to know, how to find text1 and text2 in a file? Commented May 19, 2013 at 23:36
  • using file() to read textfile, and do some processing here Commented May 19, 2013 at 23:48

1 Answer 1

5

Do it like this:

$fileTokens = explode(PHP_EOL, file_get_contents('file.txt'));
$textTokens = explode(' ', "I want to get text1 and text2");

$results = array_intersect($fileTokens, $textTokens);
var_dump($results);

To get the results as a space-delimited string, use this line

$stringResults = implode(' ', $results);
var_dump($stringResults);
Sign up to request clarification or add additional context in comments.

1 Comment

congrats on reaching 3k :)

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.