2012-02-09 4 views
4

jQuery/JavaScript에 일부 PHP 코드를 추가하는 데 도움이 필요합니까? 내가 원하는 것은 간단한 BBCode to HTML 변환기이다.JavaScript/jQuery를 사용하여 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); 

도움 주셔서 감사합니다.

답변

7

방금 ​​ig/#is을 변경할 필요가 거의 다 같은데하지만 나는 또한 \/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; 
/b을 변경했다
+0

javascript/jQuery에서 사용할 함수 이름을 모르겠습니다. 나는 PHP에서와 같이 preg_replace가 아닌 것으로 생각한다. –

+0

@piers는 – mplungjan

+0

업데이트를 참조하십시오. 고맙습니다. –