The first example is bad, because it creates function for every line it processes. When the file has many lines, you could easily run out of memory. The code should be changed so, that create_function() is used outside of loop.
preg_replace_callback
(PHP 4 >= 4.0.5, PHP 5)
preg_replace_callback — Executa uma busca usando expressão regular e modifica usando um callback
Descrição
O comportamento desta função é quase idêntico ao da preg_replace(), exceto pelo fato que ao invés do parâmetro replacement , você deve especificar um callback .
Parâmetros
- pattern
-
A padrão usado para busca. Pode ser tanto uma string como um array de strings.
- callback
-
Um callback que será chamado e passado um array dos elementos combinados na string subject . O callback deve retornar a string substituta.
Você normalmente precisará da função callback para uma preg_replace_callback() somente para isso. Neste caso você pode usar create_function() para declarar uma função anônima como callback dentro da chamada da preg_replace_callback(). Desta forma você tem todas as informações para a chamada no mesmo lugar e não cria desordem com o nome da função do callback não usado em outro lugar.
Exemplo #1 preg_replace_callback() e create_function()
<?php
/* a unix-style command line filter to convert uppercase
* letters at the beginning of paragraphs to lowercase */
$fp = fopen("php://stdin", "r") or die("can't read stdin");
while (!feof($fp)) {
$line = fgets($fp);
$line = preg_replace_callback(
'|<p>\s*\w|',
create_function(
// single quotes are essential here,
// or alternative escape all $ as \$
'$matches',
'return strtolower($matches[0]);'
),
$line
);
echo $line;
}
fclose($fp);
?> - subject
-
A string ou array com strings para procurar e modificar.
- limit
-
O máximo de possíveis modificações para cada padrão em cada string subject . O padrão é -1 (sem limite).
- count
-
Se especificado, esta variável irá ser preenchida com o número de substituições feitas.
Valor Retornado
preg_replace_callback() retorna um array se o parâmetro subject for um array, ou uma string caso contrário.
Se ocorrer combinação, a nova string será retornada, caso contrário subject será retornada inalterável.
Histórico
| Versão | Descrição |
|---|---|
| 5.1.0 | O parâmetro count foi adicionado |
Exemplos
Exemplo #2 Exemplo da preg_replace_callback()
<?php
// this text was used in 2002
// we want to get this up to date for 2003
$text = "April fools day is 04/01/2002\n";
$text.= "Last christmas was 12/24/2001\n";
// the callback function
function next_year($matches)
{
// as usual: $matches[0] is the complete match
// $matches[1] the match for the first subpattern
// enclosed in '(...)' and so on
return $matches[1].($matches[2]+1);
}
echo preg_replace_callback(
"|(\d{2}/\d{2}/)(\d{4})|",
"next_year",
$text);
?>
O exemplo acima irá imprimir:
April fools day is 04/01/2003 Last christmas was 12/24/2002
Exemplo #3 preg_replace_callback() usando estrutura recursiva para manipular BB code aninhado
<?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;
?>
preg_replace_callback
20-May-2008 07:14
24-Jun-2007 08:56
preg_replace_callback returns NULL when pcre.backtrack_limit is reached; this sometimes occurs faster then you might expect. No error is raised either; so don't forget to check for NULL yourself
26-Apr-2006 06:16
it is much better on preformance and better practice to use the preg_replace_callback function instead of preg_replace with the e modifier.
function a($text){return($text);}
// 2.76 seconds to run 50000 times
preg_replace("/\{(.*?)\}/e","a('\\1','\\2','\\3',\$b)",$a);
// 0.97 seconds to run 50000 times
preg_replace_callback("/\{(.*?)\}/s","a",$a);
