2010-07-05 68 views
0

我在尝试旋转文章时需要帮助。我想查找文本并替换同义文本,同时保持大小写不变。查找字符串并用相同大小写字符串替换

例如,我有一个像一本字典:

招呼|喜|你好| howd'y

我需要找到所有hello并与hihowdy任何一个取代,或howd'y

假设我有一个句子:

喂,伙计们!当我说你嗨,你不应该打招呼吗?

我的操作后,它会是这样的:

嗨,伙计们!当我说你好时,你不应该对我说几句吗?

在这里,我失去了这种情况。我想保持它!它应该是:

嗨,伙计们!当我说出HOWDY时,你不应该对我说多少?

我的字典大小是约5000线

招呼|喜|你好| howd'y去|来
工资|盈利|工资
不应该|不该
..

回答

1

我建议使用preg_replace_callback回调函数检查匹配的单词,看看是否(a)第一个字母没有大写,或(b)t他的第一个字母是唯一的大写字母,或者(c)第一个字母不是唯一的大写字母,然后根据需要替换为正确修改的替换字。

+0

琥珀, 谢谢您的回答。我现在也相信我需要使用preg_replace和回调。我的str_ireplace将立即替换这个词的所有实例!所以我不能保持适当的情况下不同的单词! 但你提出的三个条件,在我的脑海里早些时候:)。但是,因为我没有考虑回调函数,所以我的解决方案不会工作。所以你得到学分:)。 – HungryCoder 2010-07-05 19:44:45

0

你可以找到你的字符串,并做两个测试:

$outputString = 'hi'; 
if ($foundString == ucfirst($foundString)) { 
    $outputString = ucfirst($outputString); 
} else if ($foundString == strtoupper($foundString)) { 
    $outputString = strtoupper($outputString); 
} else { 
    // do not modify string's case 
} 
+0

是的,这是我计划要做的事情。但在HOW中可能会有所不同! :)。然而,你的意见肯定会有所帮助。非常感谢您的宝贵时间! – HungryCoder 2010-07-05 19:47:29

0

下面是保留的情况下(上,下或资本)的解决方案:

// Assumes $replace is already lowercase 
function convertCase($find, $replace) { 
    if (ctype_upper($find) === true) 
    return strtoupper($replace); 
    else if (ctype_upper($find[0]) === true) 
    return ucfirst($replace); 
    else 
    return $replace; 
} 

$find = 'hello'; 
$replace = 'hi'; 

// Find the word in all cases that it occurs in 
while (($pos = stripos($input, $find)) !== false) { 
    // Extract the word in its current case 
    $found = substr($input, $pos, strlen($find)); 

    // Replace all occurrences of this case 
    $input = str_replace($found, convertCase($found, $replace), $input); 
} 
+0

感谢您的输入! – HungryCoder 2010-07-05 19:50:17

0

你可以试试下面的函数。请注意,它仅适用于ASCII字符串,因为它使用了一些有用的properties of ASCII upper and lower case letters。然而,它应该是非常快:

function preserve_case($old, $new) { 
    $mask = strtoupper($old)^$old; 
    return strtoupper($new) | $mask . 
     str_repeat(substr($mask, -1), strlen($new) - strlen($old)); 
} 

echo preserve_case('Upper', 'lowercase'); 
// Lowercase 

echo preserve_case('HELLO', 'howdy'); 
// HOWDY 

echo preserve_case('lower case', 'UPPER CASE'); 
// upper case 

echo preserve_case('HELLO', "howd'y"); 
// HOWD'Y 

这是我的聪明的小Perl函数的PHP版本:

How do I substitute case insensitively on the LHS while preserving case on the RHS?

+0

非常感谢您的意见! – HungryCoder 2010-07-05 19:45:12

+0

我想我可以使用它!我的主题只有ASCII!所以不会成为问题! – HungryCoder 2010-07-05 19:49:47

相关问题