【问题标题】:filter words on a string in PHP在 PHP 中过滤字符串上的单词
【发布时间】:2012-06-01 16:53:30
【问题描述】:

我有一个字符串,其中每个单词的所有开头都大写。现在我想过滤它,如果它可以检测到单词链接“as, the, of, in, etc”,它将被转换为小写。我有一个代码可以替换并将其转换为小写,但只有 1 个单词,如下所示:

$str = "This Is A Sample String Of Hello World";
$str = preg_replace('/\bOf\b/', 'of', $str);

output: This Is A Sample String of Hello World

所以我想要的是过滤其他单词,例如像“is, a”这样的字符串。为每个要过滤的单词重复 preg_replace 很奇怪。

谢谢!

【问题讨论】:

  • ...将所有单词组合成一个正则表达式也很奇怪。

标签: php string preg-replace


【解决方案1】:

使用preg_replace_callback():

$str = "This Is A Sample String Of Hello World";
$str = ucfirst(preg_replace_callback(
       '/\b(Of|Is|A)\b/',
       create_function(
           '$matches',
           'return strtolower($matches[0]);'
       ),
       $str
   ));
echo $str;

Displays "This is a Sample String of Hello World".

【讨论】:

【解决方案2】:

既然您知道确切的单词和格式,您应该使用str_replace 而不是 preg_replace;它要快得多。

$text = str_replace(array('Is','Of','A'),array('is','of','a'),$text);

【讨论】:

    【解决方案3】:

    试试这个:

    $words = array('Of', 'Is', 'A', 'The');  // Add more words here
    
    echo preg_replace_callback('/\b('.implode('|', $words).')\b/', function($m) {
        return strtolower($m[0]);
    }, $str);
    
    
    // This is a Sample String of Hello World
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-07-12
      • 1970-01-01
      • 1970-01-01
      • 2018-05-13
      • 2017-02-27
      • 1970-01-01
      • 2017-11-30
      相关资源
      最近更新 更多