我使用这个代码,一切都好,它隐藏文本从$comments
之间包含[]
,但我想隐藏文本从其他符号为。例:** && ^^ $$ ## // <>
。我需要在这里添加的是INSTEAD OF
Date <20.02.2013> Time [11-00] Name #John#
有:
Date Time Name
?
function replaceTags($startPoint, $endPoint, $newText, $source) {
return preg_replace('#('.preg_quote($startPoint).')(.*)('.preg_quote($endPoint).')#si', '$1'.$newText.'$3', $source);
}
$source= $comments;
$startPoint='[';
$endPoint=']';
$newText='';
echo replaceTags($startPoint, $endPoint, $newText, $source);
你只需要改变
$startPoint='[';
$endPoint=']';
$startPoint='<';
$endPoint='>';
要处理多个符号,可以多次调用函数,如下所示:
$source= $comments;
$newText='';
$str = replaceTags('[', ']', $newText, $source);
$str = replaceTags('<', '>', $newText, $str);
$str = replaceTags('*', '*', $newText, $str);
$str = replaceTags('&', '&', $newText, $str);
$str = replaceTags('^', '^', $newText, $str);
$str = replaceTags('$', '$', $newText, $str);
$str = preg_replace("/'#[^#]+#)/","",$str);
$str = replaceTags('/', '/', $newText, $str);
// add more here
echo $str;
您必须为每一对创建模式:
$pairs = array(
'*' => '*',
'&' => '&',
'^' => '^',
'$' => '$',
'#' => '#',
'/' => '/',
'[' => ']', // this
'<' => '>', // and this pairs differently from the rest
);
$patterns = array();
foreach ($pairs as $start => $end) {
$start = preg_quote($start, '/');
$end = preg_quote($end, '/');
$patterns[] = "/($start)[^$end]*($end)/";
}
echo preg_replace($patterns, '', $s), PHP_EOL;
// not sure what you want here
// echo preg_replace($patterns, '$1' . $newText . '$2', $s), PHP_EOL;