PHP字符串替换加载文本文件

时间:2015-12-06 19:32:14

标签: php

我知道如何使用PHP str_replace替换字符串。我有代码多个字符串替换它工作正常

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

我已经在文本文件中逐一添加了许多单词,如

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

并命名为' replace.txt' 现在我的问题是如何为字符串替换功能替换为空

加载此文本文件

2 个答案:

答案 0 :(得分:1)

虽然问题没有明确说明,但我认为基本上是这样的:你有一个带文字的文件(即用空格分隔的单词),你想要删除列表中出现的所有单词。

假设$text包含要处理的文本,并$terms包含您在上面发布的行。将两者都变成一个数组:

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

当然,您可能需要额外的处理来摆脱标点符号和其他内容,但array_diff本质上就是这项工作。

答案 1 :(得分:1)

试试这个

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

我编辑了这个,所以replace.txt是被删除的术语

相关问题