0

well i know that how to replace string using PHP str_replace. I have code for multiple string replace it works fine

$subject = 'afsdfasdfasdfasd #%^#^%#@@';
$string = array('a','b','c','d','e','@','#','%','!');
echo str_replace($string, '', $subject);

i have put many words on text file one by one like

01
02
03
04
05
06
07
08
09
http://
stackoverflow.com
questions
ask
gfx
value
words
that
i want 
not
like
to
appear
in 
title

and named it 'replace.txt' now my question is how i can load this text file for string replace function replace with empty

5
  • I would suggest by using phps file functions to open and read the lines, one by one, into an array. Or reading it at once and exploding the content afterwards into an array. What is the question here? Commented Dec 6, 2015 at 19:34
  • Do you want to use the values in replace.txt as the array you pass as the first parameter to str_replace? Commented Dec 6, 2015 at 19:38
  • Take a look at: file() Commented Dec 6, 2015 at 19:39
  • do you mean file_get_content() ? Commented Dec 6, 2015 at 19:40
  • yes , Terminus you are right Commented Dec 6, 2015 at 20:02

2 Answers 2

1

Try this

$text = file_get_contents("replace.txt"); $terms = explode("\n", $text); $string = "Hello World"; $string = str_replace($terms, '', $string); echo($string);

I edited this so replace.txt is the terms that are removed

Sign up to request clarification or add additional context in comments.

6 Comments

Adrian Webster , good reply but i want replace.txt into $string place
Replace.txt is in $text
I edited the answer, the original replace.txt is in $text and the replaced replace.txt is in $ntext
Sorry I didn't understand what you wanted, try the answer now :)
The terms in replace.txt seperated by newlines will be replaced with blank
|
1

Although the question isn't clearly stated, I suppose it's essentially this: You have a file with text (i.e. words separated by spaces) and you want to delete all words that occur in the list.

Assume $text contains the text to process, and $terms the lines like you posted above. Turn both into an array:

 $text = explode(' ', $text);
 $terms = explode("\n", $terms);
 $text = array_diff($text, $terms);
 $text = implode(' ', $text);

Of course you may need extra processing to get rid of punctuation and other stuff, but array_diff is essentially what does the job.

Comments

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.