在Word中匹配和加密少量字符

时间:2013-01-30 17:42:54

标签: php

我正在开发一个筛选逻辑,其中完整的内容文本通过正则表达式与php中的关键字列表匹配。 我使用以下代码正确匹配单词并使其变为粗体。

$pattern = "/mango|apple|banana/";
$text = "i like banana and apple alot";
$replacement = "<strong>$0</strong>";
echo preg_replace($pattern, $replacement, $text);

此代码正确匹配并使匹配的单词包含在强大的

i like <strong>banana</strong> and <strong>apple</strong> alot.

但我想将香蕉替换为

b****a and apple as a****e 

而不是大胆。

任何人都可以帮助我如何做到这一点。

2 个答案:

答案 0 :(得分:2)

您可以尝试使用preg_replace_callback代替preg_replace

preg_replace_callback($pattern, function($matches){
    $str = $matches[0];
    $len = strlen($str);
    $stars = str_repeat('*', $len-2);
    return $str[0].$stars.$str[$len-1];
}, $text);

更新以创建动态数量的星星

答案 1 :(得分:1)

如果您的模式已修复,您可能希望将数组传递给preg_replace,如下所示:

$patterns = array(
    '/mango/',
    '/apple/',
    '/banana/'
}
$replacements = array(
    'm***o',
    'a***e',
    'b****a'
)
echo preg_replace($patterns, $replacements, $text);

这也适用于您想要替换的任何给定关键字数组,如下所示:

$keywords; // array populated with key words
$patterns = array();
$replacements = array();
array_walk($keywords, function($value, $key) {
    $patterns[] = '/' . $value . '/';
    $replacements[] = strpad($value[0], strlen($value) - 1, '*') . $value[strlen($value) - 1];
}
echo preg_replace($patterns, $replacements, $text);