Конвертировать BBcode в HTML используя JavaScript / jQuery - PullRequest
4 голосов
/ 09 февраля 2012

Не могли бы вы мне помочь с обработкой кода 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);

Спасибо за вашу помощь!

1 Ответ

7 голосов
/ 09 февраля 2012

Выглядит ПОЧТИ как будто вам просто нужно изменить # на / и is на ig, но мне также пришлось изменить /b на \/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;
...