AvatarLand Razer AvatarLand Razer - 3 months ago 26
PHP Question

reverse bb-codes when echo

I have found a code to use bb-codes in my personal message on profiles, but when i go back to settings to change the message it echo html tags instead of the bb-codes replacement.

bb-codes :

if(isset($_POST['submit'])) {

if(isset($_POST['bio_message'])){
//BBCode Parser function
function showBBcodes($text) {
// BBcode array
$find = array(
'~\[b\](.*?)\[/b\]~s',
'~\[i\](.*?)\[/i\]~s',
'~\[u\](.*?)\[/u\]~s',
'~\[quote\](.*?)\[/quote\]~s',
'~\[url\]((?:ftp|https?)://.*?)\[/url\]~s',
'~\[img\](https?://.*?\.(?:jpg|jpeg|gif|png|bmp))\[/img\]~s'
);
// HTML tags to replace BBcode
$replace = array(
'<b>$1</b>',
'<i>$1</i>',
'<p style="text-decoration:underline;">$1</p>',
'<pre>$1</'.'pre>',
'<a href="$1">$1</a>',
'<img src="$1" alt="" />'
);
// Replacing the BBcodes with corresponding HTML tags
return preg_replace($find,$replace,$text);
}
// How to use the above function:
$text = $_POST['bio_message'];
$htmltext = showBBcodes($text);

}

$id = htmlentities($_SESSION['user']['id'], ENT_QUOTES, 'UTF-8');

$bio_sql = "UPDATE users SET bio = '$htmltext' WHERE id = '$id'";
$db->query($bio_sql);
}else{}


echo bio in textarea:

<?php
$id = htmlentities($_SESSION['user']['id'], ENT_QUOTES, 'UTF-8');
$SQL = "SELECT * FROM users WHERE id = '$id'";


$result = $db->query($SQL);

/* associative array */
$row = $result->fetch_array(MYSQLI_ASSOC);
print(htmlentities($row['bio'], ENT_QUOTES, 'UTF-8'));

$result->free();
?>

Answer

Try this function

function showHTML($text) {
    // HTML tags to replace
    $find = array(
        '~<b>(.*?)</b>~s',
        '~<i>(.*?)</i>~s',
        '~<p style="text-decoration:underline;">(.*?)</p>~s',
        '~<pre>(.*?)</pre>~s',
        '~<a href="(.*?)">(.*?)</a>~s',
        '~<img src="(.*?)" alt="" />~s'
    );

    // BBcode array
    $replace = array(
        '[b]$1[/b]',
        '[i]$1[/i]',
        '[u]$1[/u]',
        '[quote]$1[/quote]',
        '[url]$1[/url]',
        '[img]$1[/img]'
    );

    // Replacing the BBcodes with corresponding HTML tags
    return preg_replace($find,$replace,$text);
}

Input:

<i>fsfsdfsf</i> <a href="http://abc.de">http://abc.de</a>

Output:

[i]fsfsdfsf[/i] [url]http://abc.de[/url]