我有以下正则表达式来匹配><
:/(\\\>\\\<)/
。但是当我使用那个正则表达式时没有任何反应。
如何匹配><
并将其转换为图像?
如果你需要整个功能来看我的样子:
function bbcode($string) {
# GLOBAL
global $folder_smileys;
# VARIABLE
$hashtag = str_replace('|', '', $string);
$string = nl2br($string);
$icon_div_1 = '<div class="icon-inplace" style="background-image: url(';
$icon_div_2 = ');"></div>';
# ARRAY
$codes = Array(
'/\[b\](.+?)\[\/b\]/' => '<div class="font-bold">\1</div>',
'/\[i\](.+?)\[\/i\]/' => '<div class="font-italic">\1</div>',
'/\[s\](.+?)\[\/s\]/' => '<div class="font-strikethrough">\1</div>',
'/\[url=(.+?)\](.+?)\[\/url\]/' => '<a href="\1" target="_blank">\2</a>',
'/:\)/' => $icon_div_1 . url($folder_smileys.'smiley-1f642.png') . $icon_div_2,
'/;\)/' => $icon_div_1 . url($folder_smileys.'smiley-1f609.png') . $icon_div_2,
'/:\//' => $icon_div_1 . url($folder_smileys.'smiley-1f615.png') . $icon_div_2,
'/:\(/' => $icon_div_1 . url($folder_smileys.'smiley-1f641.png') . $icon_div_2,
'/:O/' => $icon_div_1 . url($folder_smileys.'smiley-1f632.png') . $icon_div_2,
'/:P/' => $icon_div_1 . url($folder_smileys.'smiley-1f61b.png') . $icon_div_2,
'/-.-/' => $icon_div_1 . url($folder_smileys.'smiley-1f611.png') . $icon_div_2,
'/\^\^/' => $icon_div_1 . url($folder_smileys.'smiley-1f604.png') . $icon_div_2,
'/:@/' => $icon_div_1 . url($folder_smileys.'smiley-1f621.png') . $icon_div_2,
'/<3/' => $icon_div_1 . url($folder_smileys.'symbol-2764.png') . $icon_div_2,
'/O.o/' => $icon_div_1 . url($folder_smileys.'smiley-1f924.png') . $icon_div_2,
'/\(Y\)/' => $icon_div_1 . url($folder_smileys.'symbol-1f44d-1f3fb.png') . $icon_div_2,
'/(\\\>\\\<)/' => $icon_div_1 . url($folder_smileys.'smiley-1f616.png') . $icon_div_2
);
# OUTPUT
return preg_replace(array_keys($codes), array_values($codes), $string);
}
echo bbcode('><'); // Outputs >< and not as an image
答案 0 :(得分:1)
更清楚:
function bbcode($string) {
$smileys = [ ':)' => $icon_div_1 . url($folder_smileys. 'smiley-1f642.png') . $icon_div_2,
';)' => $icon_div_1 . url($folder_smileys. 'smiley-1f649.png') . $icon_div_2,
// etc.
];
$result = strtr($string, $smileys);
$codes = [
'~\[b](.+?)\[/b]~s' => '<div class="font-bold">\1</div>',
'~\[i](.+?)\[/i]~s' => '<div class="font-italic">\1</div>',
'~\[s](.+?)\[/s]~s' => '<div class="font-strikethrough">\1</div>',
'~\[url=(.+?)](.+?)\[/url]~s' => '<a href="\1" target="_blank">\2</a>',
];
$result = preg_replace(array_keys($codes), $codes, $result);
return $result;
}
您需要先替换表情符号,否则粗体,斜体和网址代码生成的尖括号可能会被覆盖。
你必须明白,当你给preg_replace
(或str_replace
一个数组时,行为是相同的),该函数接受第一项,继续替换并产生一个新的字符串,然后下一个项目使用这个新字符串并继续下一个替换。为了说明这种行为,如果你写这样的东西:
$string = 'az';
$rep = [ '~a~' => 'z',
'~z~' => 'a' ];
echo preg_replace(array_keys($rep), $rep, $string);
您将获得&#34; aa&#34; (循环替换的原因:"az" -> "zz" -> "aa"
)。
strtr
表现不同,只解析一次字符串(无论替换对的数量是多少)。
$string = 'az';
$rep = [ 'a' => 'z',
'z' => 'a' ];
echo strtr($string, $rep);
它返回&#34; za&#34; (一遍)。