我想用除div之外的特定字符串替换某些字符。这是我的str_replace:
// smileys
$in = array(
':)',
':D',
':o',
':p',
':(',
';)',
'xD',
'^^',
);
$out = array(
'<img alt=":)" style="padding-left:3px;" src="img/emoticons/emoticon_smile.png" />',
'<img alt=":D" style="padding-left:3px;" src="img/emoticons/emoticon_happy.png" />',
'<img alt=":o" style="padding-left:3px;" src="img/emoticons/emoticon_surprised.png" />',
'<img alt=":p" style="padding-left:3px;" src="img/emoticons/emoticon_tongue.png" />',
'<img alt=":(" style="padding-left:3px;" src="img/emoticons/emoticon_unhappy.png" />',
'<img alt=";)" style="padding-left:3px;" src="img/emoticons/emoticon_wink.png" />',
'<img alt="xD" style="padding-left:3px;" src="img/emoticons/emoticon_evilgrin.png" />',
'<img alt="^^" style="padding-left:3px;" src="img/emoticons/emoticon_happy.png" />'
);
$text = str_replace($in, $out, $text);var $text可以使用<div class="code-geshi"></div>,但我不想让str_replace用于表情符号。我该怎么做呢?
谢谢:)
附言:很抱歉我的英文不好…
发布于 2011-01-09 05:45:06
您不能使用str_replace做到这一点。使用preg_replace!
发布于 2011-01-09 10:33:18
我用了一种不同的方式。在我解析代码函数中:
$text = preg_replace_callback('/\[code\="?(.*?)"?\](.*?)\[\/code\]/ms', "gen_geshi", $text);我通过添加字符来替换潜在的笑脸符号:
if (!function_exists('gen_geshi')) {
function gen_geshi($s){
global $text;
$result = "";
$list_languages = array('html4strict', 'php', 'javascript', 'css');
$name_languages = array(
'html4strict' => 'HTML',
'php' => 'PHP',
'javascript' => 'Javascript',
'css' => 'CSS'
);
$text = strip_tags($text);
$language = $s[1];
$code = $s[2];
$smileys_in = array(
':)',
':D',
':o',
':p',
':(',
';)',
'xD',
'^^',
);
$smileys_out = array(
'**-|-**:**-|-**)**-|-**',
'**-|-**:**-|-**D**-|-**',
'**-|-**:**-|-**o**-|-**',
'**-|-**:**-|-**p**-|-**',
'**-|-**:**-|-**(**-|-**',
'**-|-**;**-|-**)**-|-**',
'**-|-**x**-|-**D**-|-**',
'**-|-**^**-|-**^**-|-**',
);
$code = str_replace($smileys_in, $smileys_out, $code);
if( in_array($language, $list_languages) && !empty($code) ){
global $lang;
$code = trim(preg_replace('#\t#', ' ', $code));
if (!class_exists('GeSHi')) include('inc/geshi/geshi.php');
$geshi = new GeSHi($code, $language);
$geshi->enable_line_numbers(GESHI_NORMAL_LINE_NUMBERS);
$result = '<div class="code-geshi-overall">' . $lang->get['global']['code'] . ' ' . $name_languages[$language] . ' : </div><div class="code-geshi">' . $geshi->parse_code() . '</div>';
}
return $result;
}
}然后我使用了一个str_replace:
$text = str_replace('**-|-**', '', $text);https://stackoverflow.com/questions/4636291
复制相似问题