mirror of
https://github.com/php/doc-pt_br.git
synced 2026-03-23 22:52:12 +01:00
283 lines
8.7 KiB
XML
283 lines
8.7 KiB
XML
<?xml version="1.0" encoding="utf-8"?>
|
|
<!-- EN-Revision: c1f37a6c270aadbbb3da56a3973ffd62197adf2b Maintainer: leonardolara Status: ready --><!-- CREDITS: felipe, adiel, felipe, leonardolara -->
|
|
<refentry xml:id="function.preg-replace-callback" xmlns="http://docbook.org/ns/docbook">
|
|
<refnamediv>
|
|
<refname>preg_replace_callback</refname>
|
|
<refpurpose>Executa uma busca por expressão regular e substitui usando uma chamada de retorno</refpurpose>
|
|
</refnamediv>
|
|
|
|
<refsect1 role="description">
|
|
&reftitle.description;
|
|
<methodsynopsis>
|
|
<type class="union"><type>string</type><type>array</type><type>null</type></type><methodname>preg_replace_callback</methodname>
|
|
<methodparam><type class="union"><type>string</type><type>array</type></type><parameter>pattern</parameter></methodparam>
|
|
<methodparam><type>callable</type><parameter>callback</parameter></methodparam>
|
|
<methodparam><type class="union"><type>string</type><type>array</type></type><parameter>subject</parameter></methodparam>
|
|
<methodparam choice="opt"><type>int</type><parameter>limit</parameter><initializer>-1</initializer></methodparam>
|
|
<methodparam choice="opt"><type>int</type><parameter role="reference">count</parameter><initializer>&null;</initializer></methodparam>
|
|
<methodparam choice="opt"><type>int</type><parameter>flags</parameter><initializer>0</initializer></methodparam>
|
|
</methodsynopsis>
|
|
<para>
|
|
O comportamento desta função é quase idêntico ao da
|
|
<function>preg_replace</function>, exceto pelo fato de que ao invés do parâmetro
|
|
<parameter>replacement</parameter>, deve-se especificar o parâmetro
|
|
<parameter>callback</parameter>.
|
|
</para>
|
|
</refsect1>
|
|
|
|
<refsect1 role="parameters">
|
|
&reftitle.parameters;
|
|
<para>
|
|
<variablelist>
|
|
<varlistentry>
|
|
<term><parameter>pattern</parameter></term>
|
|
<listitem>
|
|
<para>
|
|
A padrão usado para a busca. Pode ser tanto uma string como um array
|
|
de strings.
|
|
</para>
|
|
</listitem>
|
|
</varlistentry>
|
|
<varlistentry>
|
|
<term><parameter>callback</parameter></term>
|
|
<listitem>
|
|
<para>
|
|
Uma função de retorno que será chamada e passado um array dos elementos correspondentes
|
|
na string <parameter>subject</parameter>. A função deve
|
|
retornar a string substituta. Esta é a assinatura da função de retorno:
|
|
</para>
|
|
<para>
|
|
<methodsynopsis>
|
|
<type>string</type><methodname><replaceable>handler</replaceable></methodname>
|
|
<methodparam><type>array</type><parameter>matches</parameter></methodparam>
|
|
</methodsynopsis>
|
|
</para>
|
|
<para>
|
|
Normalmente será necessária uma função <parameter>callback</parameter>
|
|
para <function>preg_replace_callback</function> em apenas um lugar.
|
|
Neste caso pode-se usar uma
|
|
<link linkend="functions.anonymous">função anônima</link> para
|
|
declarar a função de retorno dentro da chamada a
|
|
<function>preg_replace_callback</function>. Desta forma,
|
|
todas as informações para a chamada estarão no mesmo lugar e
|
|
não poluem o espaço de nomes com um nome de função que não é usado em nenhum
|
|
outro lugar.
|
|
</para>
|
|
<para>
|
|
<example>
|
|
<title><function>preg_replace_callback</function> e
|
|
função anônima</title>
|
|
<programlisting role="php" annotations="non-interactive">
|
|
<![CDATA[
|
|
<?php
|
|
/* um filtro de linha de comando em estilo Unix para converter maiúsculas
|
|
* no início de parágrafos para letras minúsculas */
|
|
$fp = fopen("php://stdin", "r") or die("não foi possível ler a entrada padrão");
|
|
while (!feof($fp)) {
|
|
$line = fgets($fp);
|
|
$line = preg_replace_callback(
|
|
'|<p>\s*\w|',
|
|
function ($matches) {
|
|
return strtolower($matches[0]);
|
|
},
|
|
$line
|
|
);
|
|
echo $line;
|
|
}
|
|
fclose($fp);
|
|
?>
|
|
]]>
|
|
</programlisting>
|
|
</example>
|
|
</para>
|
|
</listitem>
|
|
</varlistentry>
|
|
<varlistentry>
|
|
<term><parameter>subject</parameter></term>
|
|
<listitem>
|
|
<para>
|
|
A string ou array com strings para procurar e modificar.
|
|
</para>
|
|
</listitem>
|
|
</varlistentry>
|
|
<varlistentry>
|
|
<term><parameter>limit</parameter></term>
|
|
<listitem>
|
|
<para>
|
|
O máximo de possíveis substituições para cada expressão em cada string de
|
|
<parameter>subject</parameter>. O padrão é
|
|
<literal>-1</literal> (sem limite).
|
|
</para>
|
|
</listitem>
|
|
</varlistentry>
|
|
<varlistentry>
|
|
<term><parameter>count</parameter></term>
|
|
<listitem>
|
|
<para>
|
|
Se especificado, esta variável será preenchida com o número de
|
|
substituições feitas.
|
|
</para>
|
|
</listitem>
|
|
</varlistentry>
|
|
<varlistentry>
|
|
<term><parameter>flags</parameter></term>
|
|
<listitem>
|
|
<para>
|
|
<parameter>flags</parameter> pode ser uma combinação das opções
|
|
<constant>PREG_OFFSET_CAPTURE</constant> e
|
|
<constant>PREG_UNMATCHED_AS_NULL</constant>, que influenciam o
|
|
formato do array de correspondências.
|
|
Veja a descrição em <function>preg_match</function> para mais detalhes.
|
|
</para>
|
|
</listitem>
|
|
</varlistentry>
|
|
</variablelist>
|
|
</para>
|
|
</refsect1>
|
|
|
|
<refsect1 role="returnvalues">
|
|
&reftitle.returnvalues;
|
|
<para>
|
|
<function>preg_replace_callback</function> retorna um array se o parâmetro
|
|
<parameter>subject</parameter> for um array, ou uma string
|
|
caso contrário. Em caso de erro o valor de retorno é &null;.
|
|
</para>
|
|
<para>
|
|
Se ocorrer correspondência, a nova string será retornada, caso contrário
|
|
<parameter>subject</parameter> será retornada inalterada.
|
|
</para>
|
|
</refsect1>
|
|
|
|
<refsect1 role="errors">
|
|
&reftitle.errors;
|
|
&pcre.pattern.warning;
|
|
</refsect1>
|
|
|
|
<refsect1 role="changelog">
|
|
&reftitle.changelog;
|
|
<para>
|
|
<informaltable>
|
|
<tgroup cols="2">
|
|
<thead>
|
|
<row>
|
|
<entry>&Version;</entry>
|
|
<entry>&Description;</entry>
|
|
</row>
|
|
</thead>
|
|
<tbody>
|
|
<row>
|
|
<entry>7.4.0</entry>
|
|
<entry>
|
|
O parâmetro <parameter>flags</parameter> foi adicionado.
|
|
</entry>
|
|
</row>
|
|
</tbody>
|
|
</tgroup>
|
|
</informaltable>
|
|
</para>
|
|
</refsect1>
|
|
|
|
<refsect1 role="examples">
|
|
&reftitle.examples;
|
|
<para>
|
|
<example>
|
|
<title>Exemplo de <function>preg_replace_callback</function></title>
|
|
<programlisting role="php">
|
|
<![CDATA[
|
|
<?php
|
|
// este texto foi usado em 2002
|
|
// se quisermos atualizá-lo para 2003
|
|
$text = "Dia da mentira é em 01/04/2002\n";
|
|
$text.= "Último Natal foi em 25/12/2001\n";
|
|
// a chamada de retorno
|
|
function next_year($matches)
|
|
{
|
|
// como sempre: $matches[0] é a correspondência completa
|
|
// $matches[1] é a correspondência da primeira sub-expressão
|
|
// envolvida por '(...)' e assim por diante
|
|
return $matches[1].($matches[2]+1);
|
|
}
|
|
echo preg_replace_callback(
|
|
"|(\d{2}/\d{2}/)(\d{4})|",
|
|
"next_year",
|
|
$text);
|
|
|
|
?>
|
|
]]>
|
|
</programlisting>
|
|
&example.outputs;
|
|
<screen>
|
|
<![CDATA[
|
|
Dia da mentira é em 01/04/2003
|
|
Último Natal foi em 25/12/2002
|
|
]]>
|
|
</screen>
|
|
</example>
|
|
</para>
|
|
<para>
|
|
<example>
|
|
<title><function>preg_replace_callback</function> usando estrutura recursiva
|
|
para manipular código BB encapsulado</title>
|
|
<programlisting role="php">
|
|
<![CDATA[
|
|
<?php
|
|
$input = "plain [indent] deep [indent] deeper [/indent] deep [/indent] plain";
|
|
|
|
function parseTagsRecursive($input)
|
|
{
|
|
|
|
$regex = '#\[indent]((?:[^[]|\[(?!/?indent])|(?R))+)\[/indent]#';
|
|
|
|
if (is_array($input)) {
|
|
$input = '<div style="margin-left: 10px">'.$input[1].'</div>';
|
|
}
|
|
|
|
return preg_replace_callback($regex, 'parseTagsRecursive', $input);
|
|
}
|
|
|
|
$output = parseTagsRecursive($input);
|
|
|
|
echo $output;
|
|
?>
|
|
]]>
|
|
</programlisting>
|
|
</example>
|
|
</para>
|
|
</refsect1>
|
|
|
|
<refsect1 role="seealso">
|
|
&reftitle.seealso;
|
|
<para>
|
|
<simplelist>
|
|
<member><link linkend="pcre.pattern">Expressões regulares PCRE</link></member>
|
|
<member><function>preg_replace_callback_array</function></member>
|
|
<member><function>preg_quote</function></member>
|
|
<member><function>preg_replace</function></member>
|
|
<member><function>preg_last_error</function></member>
|
|
<member><link linkend="functions.anonymous">Funções Anônimas</link></member>
|
|
</simplelist>
|
|
</para>
|
|
</refsect1>
|
|
|
|
</refentry>
|
|
<!-- Keep this comment at the end of the file
|
|
Local variables:
|
|
mode: sgml
|
|
sgml-omittag:t
|
|
sgml-shorttag:t
|
|
sgml-minimize-attributes:nil
|
|
sgml-always-quote-attributes:t
|
|
sgml-indent-step:1
|
|
sgml-indent-data:t
|
|
indent-tabs-mode:nil
|
|
sgml-parent-document:nil
|
|
sgml-default-dtd-file:"~/.phpdoc/manual.ced"
|
|
sgml-exposed-tags:nil
|
|
sgml-local-catalogs:nil
|
|
sgml-local-ecat-files:nil
|
|
End:
|
|
vim600: syn=xml fen fdm=syntax fdl=2 si
|
|
vim: et tw=78 syn=sgml
|
|
vi: ts=1 sw=1
|
|
-->
|