使用JavaScript / jQuery将BBcode转换为HTML [英] Convert BBcode to HTML using JavaScript/jQuery

查看:161
本文介绍了使用JavaScript / jQuery将BBcode转换为HTML的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我能否帮助将一些PHP代码转换为jQuery / JavaScript?我想要的是一个简单的BBCode到HTML转换器。

Could I please get some help with coverting some PHP code to jQuery/JavaScript? What I want is a simple BBCode to HTML converter.

这是PHP代码。我想用jQuery / JavaScript实现同样的目的。

Here is the PHP code. I want to achieve the same thing using jQuery/JavaScript.

$str = htmlentities($str);

// The array of regex patterns to look for
$format_search =  array(
    '#\[b\](.*?)\[/b\]#is',
    '#\[i\](.*?)\[/i\]#is',
    '#\[u\](.*?)\[/u\]#is',
);

// The matching array of strings to replace matches with
$format_replace = array(
    '<strong>$1</strong>',
    '<em>$1</em>',
    '<span style="text-decoration: underline;">$1</span>',
);

// Perform the actual conversion
$str = preg_replace($format_search, $format_replace, $str);

感谢您的帮助!

推荐答案

看起来像几乎只需要将更改为 / ig 但我还必须将 / b 更改为 \ / b

Looks ALMOST like you just need to change # to / and is to ig but I also had to change /b to \/b

现场演示

$str = 'this is a [b]bolded[/b] and [i]italic[/i] string';

// The array of regex patterns to look for
$format_search =  [
    /\[b\](.*?)\[\/b\]/ig,
    /\[i\](.*?)\[\/i\]/ig,
    /\[u\](.*?)\[\/u\]/ig
]; // note: NO comma after the last entry

// The matching array of strings to replace matches with
$format_replace = [
    '<strong>$1</strong>',
    '<em>$1</em>',
    '<span style="text-decoration: underline;">$1</span>'
];

// Perform the actual conversion
for (var i =0;i<$format_search.length;i++) {
  $str = $str.replace($format_search[i], $format_replace[i]);
}
alert($str)






其他现场演示

function boldFunc(str, p1, offset, s) {
  return '<strong>'+encodeURIComponent(p1)+'</strong>'
}

function italicFunc(str, p1, offset, s) {
  return '<em>'+encodeURIComponent(p1)+'</em>'
}

function underlinedFunc(str, p1, offset, s) {
  return '<span class="un">'+encodeURIComponent(p1)+'</span>'
}


$str = 'this is a [b]bölded[/b], [i]itälic[/i] and [u]ünderlined[/u] [i]strïng[/i]';

// The array of regex patterns to look for
$format_search =  [
    /\[b\](.*?)\[\/b\]/ig,
    /\[i\](.*?)\[\/i\]/ig,
    /\[u\](.*?)\[\/u\]/ig
]; // NOTE: No comma after the last entry

// The matching array of strings to replace matches with
$format_replace = [
    boldFunc,
    italicFunc,
    underlinedFunc
];

// Perform the actual conversion
for (var i =0;i<$format_search.length;i++) {
  $str = $str.replace($format_search[i], $format_replace[i]);
}
document.getElementById('output').innerHTML=$str;

这篇关于使用JavaScript / jQuery将BBcode转换为HTML的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆