col*_*lin 21 php regex preg-replace
我使用的preg_replace在PHP中找到并替换字符串中的特定单词,就像这样:
$subject = "Apple apple";
print preg_replace('/\bapple\b/i', 'pear', $subject);
Run Code Online (Sandbox Code Playgroud)
结果'梨梨'.
我希望能够做的是以不区分大小写的方式匹配一个单词,但是当它被替换时尊重它的情况 - 给出结果'Pear pear'.
以下作品,但对我来说似乎有点长篇大论:
$pattern = array('/Apple\b/', '/apple\b/');
$replacement = array('Pear', 'pear');
$subject = "Apple apple";
print preg_replace($pattern, $replacement, $subject);
Run Code Online (Sandbox Code Playgroud)
有一个更好的方法吗?
更新:继续下面提出的一个出色的查询,为了完成这项任务,我只想尊重'标题案例' - 所以一个单词的第一个字母是否是一个大写.
Alm*_* Do 11
我想到了常见情况的这种实现:
$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"
Run Code Online (Sandbox Code Playgroud)
- 当然,它更复杂,但适合任何职位的原始要求.如果你只找第一个字母,这可能是一个矫枉过正(请参阅@ Jon的回答)
Jon*_*Jon 10
你可以这样做preg_replace_callback,但是更长的啰嗦:
$replacer = function($matches) {
return ctype_lower($matches[0][0]) ? 'pear' : 'Pear';
};
print preg_replace_callback('/\bapple\b/i', $replacer, $subject);
Run Code Online (Sandbox Code Playgroud)
这段代码只是查看匹配的第一个字符的大写,以确定要替换的内容; 你可以调整代码来做更多涉及的事情.
这是我使用的解决方案:
$result = preg_replace("/\b(foo)\b/i", "<strong>$1</strong>", $original);
Run Code Online (Sandbox Code Playgroud)
用我能说的最好的话,我会尝试解释为什么会这样:将您的搜索词包装起来()意味着我想稍后访问这个值。由于它是 RegEx 中 pars 中的第一项,因此可以使用 访问$1,正如您在替换参数中看到的