【问题标题】:Convert BBcode to HTML using JavaScript/jQuery使用 JavaScript/jQuery 将 BBcode 转换为 HTML
【发布时间】:2012-02-09 12:17:52
【问题描述】:

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

这里是 PHP 代码。我想用 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);

感谢您的帮助!

【问题讨论】:

    标签: javascript jquery bbcode


    【解决方案1】:

    看起来您只需将# 更改为/is 更改为ig,但我还必须将/b 更改为\/b

    Live Demo

    $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)
    

    Other Live Demo

    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 中使用的函数的名称。我想它不是 PHP 中的 preg_replace。
    • 有什么方法可以在 $1 上运行函数吗?我需要在 $1 上运行 encodeURIComponent()。谢谢!
    • 谢谢你。我已经分叉了这个以包含 phpbb 和使用 jQuery jsfiddle.net/2Zfvk 的 uid bbcodes
    猜你喜欢
    • 1970-01-01
    • 2011-07-28
    • 1970-01-01
    • 2015-08-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多