PHP preg_replace:不区分大小写的匹配和区分大小写的替换 [英] PHP preg_replace: Case insensitive match with case sensitive replacement

查看:155
本文介绍了PHP preg_replace:不区分大小写的匹配和区分大小写的替换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在PHP中使用preg_replace来查找和替换字符串中的特定单词,如下所示:

I'm using preg_replace in PHP to find and replace specific words in a string, like this:

$subject = "Apple apple";
print preg_replace('/\bapple\b/i', 'pear', $subject);

哪个给出结果为'pear pear'.

Which gives the result 'pear pear'.

我想做的是以不区分大小写的方式匹配一个单词,但是在替换时请注意这种情况-给出的结果为'Pear pear'.

What I'd like to be able to do is to match a word in a case insensitive way, but respect it's case when it is replaced - giving the result 'Pear pear'.

以下作品有效,但似乎让我有些困惑:

The following works, but seems a little long winded to me:

$pattern = array('/Apple\b/', '/apple\b/');
$replacement = array('Pear', 'pear');
$subject = "Apple apple";
print preg_replace($pattern, $replacement, $subject);

有更好的方法吗?

更新:除了下面提出的一个很好的查询之外,出于此任务的目的,我只想尊重标题大小写",即单词的第一个字母是否为大写.

Update: Further to an excellent query raised below, for the purposes of this task I only want to respect 'title case' - so whether or not the first letter of a word is a capital.

推荐答案

对于普通情况,我已经想到了此实现:

I have in mind this implementation for common case:

$data    = 'this is appLe and ApPle';
$search  = 'apple';
$replace = 'pear';

$data = preg_replace_callback('/\b'.$search.'\b/i', function($matches) use ($replace)
{
   $i=0;
   return join('', array_map(function($char) use ($matches, &$i)
   {
      return ctype_lower($matches[0][$i++])?strtolower($char):strtoupper($char);
   }, str_split($replace)));
}, $data);

//var_dump($data); //"this is peaR and PeAr"

-当然更复杂,但是适合任何职位的原始要求.如果您只寻找第一个字母,这可能是一个过大的选择(请参阅@Jon的回答)

-it's more complicated, of course, but fit original request for any position. If you're looking for only first letter, this could be an overkill (see @Jon's answer then)

这篇关于PHP preg_replace:不区分大小写的匹配和区分大小写的替换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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