PHP语言中字符串上的过滤字词 [英] filter words on a string in PHP

查看:15
本文介绍了PHP语言中字符串上的过滤字词的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

output: This Is A Sample String of Hello World
所以我想要的是过滤上的其他单词,比如字符串上的"is,a"。过滤上的每个单词都要重复使用preg_place,这很奇怪。

谢谢!

推荐答案

使用preg_replace_callback()

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

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

这篇关于PHP语言中字符串上的过滤字词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆