【问题标题】:PHP string replace load text filePHP字符串替换加载文本文件
【发布时间】:2015-12-06 19:32:13
【问题描述】:

我知道如何使用 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” 现在我的问题是如何为 string replace function 加载此文本文件替换为空

【问题讨论】:

  • 我建议通过使用 phps 文件函数打开并逐行读取行到数组中。或者一次读取它,然后将内容分解成一个数组。这里有什么问题?
  • 您想使用 replace.txt 中的值作为您传递给 str_replace 的第一个参数的数组吗?
  • 看看:file()
  • 你的意思是file_get_content() 吗?
  • 是的,总站你是对的

标签: php


【解决方案1】:

试试这个

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

我对此进行了编辑,因此 replace.txt 是被删除的术语

【讨论】:

  • Adrian Webster ,很好的回复,但我想将 replace.txt 放入 $string 位置
  • Replace.txt 在 $text 中
  • 我编辑了答案,原来的replace.txt在$text中,替换后的replace.txt在$ntext中
  • 对不起,我不明白你想要什么,现在试试答案:)
  • replace.txt 中由换行符分隔的术语将被替换为空白
【解决方案2】:

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

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

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

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

【讨论】:

    猜你喜欢
    • 2012-08-07
    • 2011-12-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-17
    • 1970-01-01
    • 2011-06-30
    • 1970-01-01
    相关资源
    最近更新 更多