【问题标题】:Help with str_replace()帮助 str_replace()
【发布时间】:2011-08-16 23:46:27
【问题描述】:

我正在清理一个字符串,删除这个数组中的字符串:

$regex = array("subida", " de"," do", " da", "em", " na", " no", "blitz");

这是我正在使用的 str_replace:

for($i=0;$i<8;$i++){
    $twit = str_replace($regex[$i],'', $twit);
}

如果它恰好是字符串中的单词,我如何让它只删除一个单词,我的意思是,我有以下短语: “#blitz na subida do alfabarra blitz” 它会返回我: "# 阿尔法巴拉", 我不希望删除第一个“闪电战”,因为它有一个哈希“#”,我希望它输出: “#blitz alfabarra”,这可能吗?谢谢

【问题讨论】:

  • 变量的名称 ($regex) 具有误导性,因为您根本没有使用正则表达式。实际上,str_replace 接受并排列,所以你可以$twit = str_replace($regex,'', $twit);

标签: php regex str-replace


【解决方案1】:

这假设您的所有字符串中都没有/。如果是这样,则使用 / 作为第二个参数显式运行 preg_quote()

它还假设您要匹配单词,所以我修剪了每个单词。

$words = array("subida", " de"," do", " da", "em", " na", " no", "blitz");

$words = array_map('trim', $words);

$words = array_map('preg_quote', $words);

$str = preg_replace('/\b[^#](?:' . implode('|', $words) . ')\b/', '', $str);

Codepad.

【讨论】:

  • 对正则表达式的轻微警告:由于字符类,可能会删除诸如“ablitz”之类的词。 Regex-fu 在这里失败了,所以在单词上使用了 array_diff。
  • @cbuckley 嗯,你是对的。我得再想一想:)
【解决方案2】:

在未能想出一个包罗万象的正则表达式解决方案后,以下可能有用:

$words = array("subida", " de", " do", " da", "em", " na", " no", "blitz");
$words = array_map('trim', $words);

$str = '#blitz *blitz ablitz na subida do alfabarra blitz# blitz blitza';

$str_words = explode(' ', $str);
$str_words = array_diff($str_words, $words);
$str = implode(' ', $str_words);
var_dump($str);

解决了基于正则表达式的解决方案中单词边界的一些复杂问题。

【讨论】:

    【解决方案3】:

    试试这个:

    for($i=0; $i<$regex('count'); $i++){
        foreach($regex[$i] as $key) {
            if ( is_string($key) ) {
                $twit = str_replace($regex[$i],'', $twit);
            }
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-12-21
      • 2011-06-20
      • 2011-07-28
      • 2011-10-04
      • 2011-08-03
      • 2011-11-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多