【问题标题】:Using str_replace multiple times on the same string在同一个字符串上多次使用 str_replace
【发布时间】:2013-05-15 22:24:58
【问题描述】:

我正在循环浏览表格中的标题,所以它基本上是这样的。

foreach($c as $row){
    echo string_shorten($row['title']);
}

我正在尝试的是一个 switch 语句,它将在我希望它搜索的内容之间切换,一旦找到,用我在 str_replace 中选择的内容替换它:

function string_shorten($text){
    switch(strpos($text, $pos) !== false){
         case "Hi":
              return str_replace('Hi','Hello', $text);
         break;
    }
}

任何建议或可能的替代方案将不胜感激。感觉就像我真的很接近但不完全一样。

【问题讨论】:

  • str_replace() 将接受数组作为 from 和 to 参数 - php.net/manual/en/function.str-replace.php
  • 并非所有的字符串都会以相同的方式替换。在一种情况下,一个单词被替换为缩写,而另一个单词被完全删除。
  • 您也可以将替换设为数组
  • 您的switchcase TRUE/FALSE,并且"Hi"TRUE 相同。 php.net/language.types.type-juggling
  • @stepquick - 所以相应地构建你的替换数组

标签: php str-replace


【解决方案1】:

正如您在manual for str_replace() 中看到的那样

混合str_replace(混合$search,混合$replace,混合$subject[,int &$count])

还有这个例子

// Provides: You should eat pizza, beer, and ice cream every day
$phrase  = "You should eat fruits, vegetables, and fiber every day.";
$healthy = array("fruits", "vegetables", "fiber");
$yummy   = array("pizza", "beer", "ice cream");

$newphrase = str_replace($healthy, $yummy, $phrase);

这意味着你可以使用类似下面的东西

$search = array('Hi', 'Heyo', 'etc.');
$replace = array('Hello', 'Hello', '');
$str = str_replace($search, $replace, $str);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-03-21
    • 1970-01-01
    • 2013-07-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多