<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Blog do Beraldo &#187; formatação de texto</title>
	<atom:link href="http://www.rberaldo.com.br/blog/tag/formatacao-de-texto/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.rberaldo.com.br/blog</link>
	<description>Programação, Música, Entretenimento e o que mais me vier à mente</description>
	<lastBuildDate>Mon, 06 Feb 2012 14:30:10 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	
		<item>
		<title>Como criar sistema de BBCode</title>
		<link>http://www.rberaldo.com.br/blog/como-criar-sistema-de-bbcode/</link>
		<comments>http://www.rberaldo.com.br/blog/como-criar-sistema-de-bbcode/#comments</comments>
		<pubDate>Fri, 18 Sep 2009 12:34:08 +0000</pubDate>
		<dc:creator>Beraldo</dc:creator>
				<category><![CDATA[PHP]]></category>
		<category><![CDATA[Programação]]></category>
		<category><![CDATA[bbcode]]></category>
		<category><![CDATA[formatação de texto]]></category>
		<category><![CDATA[tags]]></category>

		<guid isPermaLink="false">http://www.rberaldo.com.br/blog/?p=61</guid>
		<description><![CDATA[O BBCode é um recurso amplamente utilizado em fóruns. Ele permite editar textos de forma simples e rápida, sendo de fácil compreensão inclusive para leigos em HTML. Neste post mostrarei como criar alguns BBCodes mais usados, como [b] (negrito), [i] (itálico), [img] (imagem), [url] (link), [youtube] (para vídeos do youtube) e outros. Basicamente, o que [...]]]></description>
			<content:encoded><![CDATA[<p>O <a href="http://pt.wikipedia.org/wiki/BBCode" target="_blank" onclick="urchinTracker('/outgoing/pt.wikipedia.org/wiki/BBCode?referer=');">BBCode</a> é um recurso amplamente utilizado em fóruns. Ele permite editar textos de forma simples e rápida, sendo de fácil compreensão inclusive para leigos em HTML.</p>
<p>Neste post mostrarei como criar alguns BBCodes mais usados, como [b] (negrito), [i] (itálico), [img] (imagem), [url] (link), [youtube] (para vídeos do youtube) e outros.</p>
<p><span id="more-61"></span><br />
Basicamente, o que precisamos para montar o sistema de BBCode é usar funções de reposicionamento (<em>replace</em>) de textos, utilizando <a href="http://pt.wikipedia.org/wiki/Express%C3%A3o_regular" target="_blank" onclick="urchinTracker('/outgoing/pt.wikipedia.org/wiki/Express_C3_A3o_regular?referer=');">Expressões Regulares</a> (ER&#8217;s), a fim de modificar apenas uma parte da string, sem perder o dado principal contido nela &#8211; o conteúdo a ser exibido com formatação.</p>
<p>Vamos começar com exemplos simples.</p>
<h3>Negrito e Itálico</h3>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
</pre></td><td class="code"><pre class="php" style="font-family:monospace;"><span style="color: #666666; font-style: italic;">// exemplo 1</span>
<span style="color: #000088;">$str</span> <span style="color: #339933;">=</span> <span style="color: #0000ff;">'exemplo de texto em [b]negrito[/b] para testar BBCode'</span><span style="color: #339933;">;</span>
<span style="color: #000088;">$str</span> <span style="color: #339933;">=</span> <span style="color: #990000;">preg_replace</span><span style="color: #009900;">&#40;</span> <span style="color: #0000ff;">&quot;/\[b\](.*?)\[\/b\]/i&quot;</span><span style="color: #339933;">,</span> <span style="color: #0000ff;">&quot;&lt;strong&gt;<span style="color: #006699; font-weight: bold;">$1</span>&lt;/strong&gt;&quot;</span><span style="color: #339933;">,</span> <span style="color: #000088;">$str</span> <span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #b1b100;">echo</span> <span style="color: #000088;">$str</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #666666; font-style: italic;">// exemplo 2</span>
<span style="color: #000088;">$str</span> <span style="color: #339933;">=</span> <span style="color: #0000ff;">'exemplo de texto em [b]negrito[/b] para testar BBCode'</span><span style="color: #339933;">;</span>
<span style="color: #000088;">$str</span> <span style="color: #339933;">=</span> <span style="color: #990000;">preg_replace</span><span style="color: #009900;">&#40;</span> <span style="color: #0000ff;">&quot;/\[(\/)?b\]/i&quot;</span><span style="color: #339933;">,</span> <span style="color: #0000ff;">&quot;&lt;<span style="color: #006699; font-weight: bold;">$1strong</span>&gt;&quot;</span><span style="color: #339933;">,</span> <span style="color: #000088;">$str</span> <span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #b1b100;">echo</span> <span style="color: #000088;">$str</span><span style="color: #339933;">;</span></pre></td></tr></table></div>

<p>A vantagem do primeiro exemplo é que, se o usuário esquecer de fechar a tag, por exemplo, o texto não ficará totalmente em negrito. Teste o segundo exemplo com a string abaixo e veja o resultado.</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
</pre></td><td class="code"><pre class="php" style="font-family:monospace;"><span style="color: #000088;">$str</span> <span style="color: #339933;">=</span> <span style="color: #0000ff;">'exemplo de texto em [b]negrito[/b para testar BBCode'</span><span style="color: #339933;">;</span></pre></td></tr></table></div>

<p>A ER irá casar (<em>match</em>) com &#8220;[b]&#8220;, inserindo a tag <strong>. Porém, não encontrará o fechamento &#8220;[/b]&#8220;, para inserir a tag </strong>. Assim, todo o texto seguinte ficará em negrito.</p>
<p>O BBCode para itálico é praticamente igual. Basta mudar [b]  para [i] e <strong> para <em>.</p>
<h3>Imagens</h3>
<p>Para inserir imagens, geralmente é usada a seguinte sintaxe:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
</pre></td><td class="code"><pre class="php" style="font-family:monospace;"><span style="color: #009900;">&#91;</span>img<span style="color: #009900;">&#93;</span>http<span style="color: #339933;">:</span><span style="color: #666666; font-style: italic;">//url_da_imagem.jpg[/img]</span></pre></td></tr></table></div>

<p>Nesse caso, usaremos o seguinte trecho para transformarmos o BBCode em HTML:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
</pre></td><td class="code"><pre class="php" style="font-family:monospace;"><span style="color: #000088;">$str</span> <span style="color: #339933;">=</span> <span style="color: #0000ff;">'[img]http://www.inf.ufpr.br/rbc08/linux_user_id.png[/img]'</span><span style="color: #339933;">;</span>
<span style="color: #000088;">$str</span> <span style="color: #339933;">=</span> <span style="color: #990000;">preg_replace</span><span style="color: #009900;">&#40;</span> <span style="color: #0000ff;">&quot;/\[img\](.*?)\[\/img\]/i&quot;</span><span style="color: #339933;">,</span> <span style="color: #0000ff;">&quot;&lt;img src=<span style="color: #000099; font-weight: bold;">\&quot;</span><span style="color: #006699; font-weight: bold;">$1</span><span style="color: #000099; font-weight: bold;">\&quot;</span> alt=<span style="color: #000099; font-weight: bold;">\&quot;</span>texto_alternativo<span style="color: #000099; font-weight: bold;">\&quot;</span> /&gt;&quot;</span><span style="color: #339933;">,</span> <span style="color: #000088;">$str</span> <span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #b1b100;">echo</span> <span style="color: #000088;">$str</span><span style="color: #339933;">;</span></pre></td></tr></table></div>

<p>A ER captura o conteúdo entre as tags [img] e [/img] e o insere no atributo src da tag img.</p>
<h3>Links</h3>
<p>Vamos assumir que o BBCode para link seja da seguinte forma:</p>
<pre>
[url=http://url_desejada]Texto que será exibido como link[/url]
</pre>
<p>Para essa situação, devemos casar duas string: a URL e o texto a ser exibido. Logo, usaremos o seguinte código:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
</pre></td><td class="code"><pre class="php" style="font-family:monospace;"><span style="color: #000088;">$str</span> <span style="color: #339933;">=</span> <span style="color: #0000ff;">'[url=http://www.rberaldo.com.br]Blog do Beraldo[/url]'</span><span style="color: #339933;">;</span>
<span style="color: #000088;">$str</span> <span style="color: #339933;">=</span> <span style="color: #990000;">preg_replace</span><span style="color: #009900;">&#40;</span> <span style="color: #0000ff;">&quot;/\[url=(.*?)\](.*?)\[\/url\]/i&quot;</span><span style="color: #339933;">,</span> <span style="color: #0000ff;">&quot;&lt;a href=<span style="color: #000099; font-weight: bold;">\&quot;</span><span style="color: #006699; font-weight: bold;">$1</span><span style="color: #000099; font-weight: bold;">\&quot;</span> target=<span style="color: #000099; font-weight: bold;">\&quot;</span>blank<span style="color: #000099; font-weight: bold;">\&quot;</span>&gt;<span style="color: #006699; font-weight: bold;">$2</span>&lt;/a&gt;&quot;</span><span style="color: #339933;">,</span> <span style="color: #000088;">$str</span> <span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #b1b100;">echo</span> <span style="color: #000088;">$str</span><span style="color: #339933;">;</span></pre></td></tr></table></div>

<p>Adicionei o atributo target para evitar que o link seja exibido na mesma página. Você pode retirá-lo. Também pode adicionar outros atributos, como <strong>rel</strong>, a fim de definir a relação do link com sua página.</p>
<h3>Texto colorido</h3>
<p>Para colorir textos, usaremos o BBCode [color=cor_desejada][texto[/color].</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
</pre></td><td class="code"><pre class="php" style="font-family:monospace;"><span style="color: #000088;">$str</span> <span style="color: #339933;">=</span> <span style="color: #0000ff;">'[color=red]texto vermelho[/color]'</span><span style="color: #339933;">;</span>
<span style="color: #000088;">$str</span> <span style="color: #339933;">=</span> <span style="color: #990000;">preg_replace</span><span style="color: #009900;">&#40;</span> <span style="color: #0000ff;">&quot;/\[color=(.*?)\](.*?)\[\/color\]/i&quot;</span><span style="color: #339933;">,</span> <span style="color: #0000ff;">&quot;&lt;spen style=<span style="color: #000099; font-weight: bold;">\&quot;</span>color: <span style="color: #006699; font-weight: bold;">$1</span><span style="color: #000099; font-weight: bold;">\&quot;</span>&gt;<span style="color: #006699; font-weight: bold;">$2</span>&lt;/span&gt;&quot;</span><span style="color: #339933;">,</span> <span style="color: #000088;">$str</span> <span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #b1b100;">echo</span> <span style="color: #000088;">$str</span><span style="color: #339933;">;</span></pre></td></tr></table></div>

<p>É possível usar nomes de cores, como green, red, blue, black etc, ou o código hexadecimal dela, no padrão #123456. </p>
<h3>Vídeos do Youtube</h3>
<p>O Youtube disponibiliza em sua página o código-fonte do vídeo exibido, a fim de permitir que você o insira em sua página. Logo, também podemos criar um BBCode para inserir vídeos, bastando inserir o código <strong>embed</strong> (incorporar) mostrado na página do Youtube, junto ao player do vídeo, como mostra a imagem abaixo:</p>
<p><img src="http://rberaldo.com.br/blog/img/youtube_embed.png" alt="Como copiar código para incorporar vídeo do youtube à sua página" /></p>
<p>O código para postagem é basicamente este:</p>

<div class="wp_syntax"><div class="code"><pre class="php" style="font-family:monospace;"><span style="color: #339933;">&lt;</span>object width<span style="color: #339933;">=</span><span style="color: #0000ff;">&quot;425&quot;</span> height<span style="color: #339933;">=</span><span style="color: #0000ff;">&quot;344&quot;</span><span style="color: #339933;">&gt;</span>
	<span style="color: #339933;">&lt;</span>param name<span style="color: #339933;">=</span><span style="color: #0000ff;">&quot;movie&quot;</span> value<span style="color: #339933;">=</span><span style="color: #0000ff;">&quot;http://www.youtube.com/v/codigo_do_video&quot;</span><span style="color: #339933;">&gt;&lt;/</span>param<span style="color: #339933;">&gt;</span>
	<span style="color: #339933;">&lt;</span>param name<span style="color: #339933;">=</span><span style="color: #0000ff;">&quot;allowFullScreen&quot;</span> value<span style="color: #339933;">=</span><span style="color: #0000ff;">&quot;true&quot;</span><span style="color: #339933;">&gt;&lt;/</span>param<span style="color: #339933;">&gt;</span>
	<span style="color: #339933;">&lt;</span>param name<span style="color: #339933;">=</span><span style="color: #0000ff;">&quot;allowscriptaccess&quot;</span> value<span style="color: #339933;">=</span><span style="color: #0000ff;">&quot;always&quot;</span><span style="color: #339933;">&gt;&lt;/</span>param<span style="color: #339933;">&gt;</span>
	<span style="color: #339933;">&lt;</span>embed src<span style="color: #339933;">=</span><span style="color: #0000ff;">&quot;http://www.youtube.com/v/codigo_do_video&quot;</span> type<span style="color: #339933;">=</span><span style="color: #0000ff;">&quot;application/x-shockwave-flash&quot;</span> allowscriptaccess<span style="color: #339933;">=</span><span style="color: #0000ff;">&quot;always&quot;</span> allowfullscreen<span style="color: #339933;">=</span><span style="color: #0000ff;">&quot;true&quot;</span> width<span style="color: #339933;">=</span><span style="color: #0000ff;">&quot;425&quot;</span> height<span style="color: #339933;">=</span><span style="color: #0000ff;">&quot;344&quot;</span><span style="color: #339933;">&gt;&lt;/</span>embed<span style="color: #339933;">&gt;</span>
<span style="color: #339933;">&lt;/</span>object<span style="color: #339933;">&gt;</span></pre></div></div>

<p>Logo, basta inserirmos o código do vídeo onde está a string &#8220;codigo_do_video&#8221;.</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
</pre></td><td class="code"><pre class="php" style="font-family:monospace;"><span style="color: #666666; font-style: italic;">// string que será usada no reposicionamento</span>
<span style="color: #000088;">$replace</span> <span style="color: #339933;">=</span> <span style="color: #0000ff;">&quot;
&lt;object width=<span style="color: #000099; font-weight: bold;">\&quot;</span>425<span style="color: #000099; font-weight: bold;">\&quot;</span> height=<span style="color: #000099; font-weight: bold;">\&quot;</span>344<span style="color: #000099; font-weight: bold;">\&quot;</span>&gt;
	&lt;param name=<span style="color: #000099; font-weight: bold;">\&quot;</span>movie<span style="color: #000099; font-weight: bold;">\&quot;</span> value=<span style="color: #000099; font-weight: bold;">\&quot;</span>http://www.youtube.com/v/<span style="color: #006699; font-weight: bold;">$1</span><span style="color: #000099; font-weight: bold;">\&quot;</span>&gt;&lt;/param&gt;
	&lt;param name=<span style="color: #000099; font-weight: bold;">\&quot;</span>allowFullScreen<span style="color: #000099; font-weight: bold;">\&quot;</span> value=<span style="color: #000099; font-weight: bold;">\&quot;</span>true<span style="color: #000099; font-weight: bold;">\&quot;</span>&gt;&lt;/param&gt;
	&lt;param name=<span style="color: #000099; font-weight: bold;">\&quot;</span>allowscriptaccess<span style="color: #000099; font-weight: bold;">\&quot;</span> value=<span style="color: #000099; font-weight: bold;">\&quot;</span>always<span style="color: #000099; font-weight: bold;">\&quot;</span>&gt;&lt;/param&gt;
	&lt;embed src=<span style="color: #000099; font-weight: bold;">\&quot;</span>http://www.youtube.com/v/<span style="color: #006699; font-weight: bold;">$1</span><span style="color: #000099; font-weight: bold;">\&quot;</span> type=<span style="color: #000099; font-weight: bold;">\&quot;</span>application/x-shockwave-flash<span style="color: #000099; font-weight: bold;">\&quot;</span> allowscriptaccess=<span style="color: #000099; font-weight: bold;">\&quot;</span>always<span style="color: #000099; font-weight: bold;">\&quot;</span> allowfullscreen=<span style="color: #000099; font-weight: bold;">\&quot;</span>true<span style="color: #000099; font-weight: bold;">\&quot;</span> width=<span style="color: #000099; font-weight: bold;">\&quot;</span>425<span style="color: #000099; font-weight: bold;">\&quot;</span> height=<span style="color: #000099; font-weight: bold;">\&quot;</span>344<span style="color: #000099; font-weight: bold;">\&quot;</span>&gt;&lt;/embed&gt;
&lt;/object&gt;&quot;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #000088;">$str</span> <span style="color: #339933;">=</span> <span style="color: #0000ff;">'[youtube]http://www.youtube.com/watch?v=YaXLlyEm4kQ&amp;feature=rec-HM-r2[/youtube]'</span><span style="color: #339933;">;</span>
<span style="color: #000088;">$str</span> <span style="color: #339933;">=</span> <span style="color: #990000;">preg_replace</span><span style="color: #009900;">&#40;</span> <span style="color: #0000ff;">&quot;/\[youtube\].+?watch\?v=([^&amp;]+).*?\[\/youtube\]/i&quot;</span><span style="color: #339933;">,</span> <span style="color: #000088;">$replace</span><span style="color: #339933;">,</span> <span style="color: #000088;">$str</span> <span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #b1b100;">echo</span> <span style="color: #000088;">$str</span><span style="color: #339933;">;</span></pre></td></tr></table></div>

<p>Criei a variável $replace para facilitar a visualização do código que será usado no <em>replace</em>. A ER desse exemplo é um pouco mais complexa, mas não é tão difícil de compreendê-la. &#8220;.+?&#8221; casa com &#8220;http://&#8221; até qualquer coisa antes de &#8220;watch&#8221;. &#8220;([^&#038;]+)&#8221; pega o código do vídeo, que não pode contar o caractere &#8220;&amp;&#8221;, que é o delimitador de variáveis da URL. Após o código do vídeo, pode ou não haver outras variáveis, por isso termina-se com &#8220;.*?&#8221;.</p>
<p>Lógica semelhante pode ser usada para Google Vídeos ou outros sites afins.</p>
<p>É possível criar BBCodes para diversas outras finalidades. Basta ter criatividade e conhecimento de ER&#8217;s, para saber montar as regras de reposicionamento.</p>
<p>Alguns links interessantes:<br />
<a href="http://guia-er.sourceforge.net" target="_blank" onclick="urchinTracker('/outgoing/guia-er.sourceforge.net?referer=');">Guia sobre Expressões Regulares</a><br />
<a href="http://br.php.net/manual/en/function.preg-replace.php" target="_blank" onclick="urchinTracker('/outgoing/br.php.net/manual/en/function.preg-replace.php?referer=');">Documentação da função preg_replace</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.rberaldo.com.br/blog/como-criar-sistema-de-bbcode/feed/</wfw:commentRss>
		<slash:comments>10</slash:comments>
		</item>
	</channel>
</rss>

