Changelog

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 functionfunction next_year($matches){// as usual: $matches[0] is the complete match // $matches[1] the match for the first subpattern // enclosed in '(...)' and so onreturn $matches[1].($matches[2]+1);}echo preg_replace_callback("|(\d{2}/\d{2}/)(\d{4})|","next_year",$text);

User Contributed Notes 27 notes

The easiest way to pass more than one parameters to the callback function is with the 'use' keyword.

[This is better than using global, because it works even when we are already inside a function.]

In this example, the callback function is an anonymous function, which takes one argument, $match, supplied by preg_replace_callback(). The extra
"use ($ten)" puts the $ten variable into scope for the function.

If you're looking to show only the first digit and last four digits of a credit card number (4xxxxxxxxxxxx2331) use something like this:preg_replace_callback('/((.)(.*))?(.{4})/', create_function('$x', 'return $x[2].str_repeat("x", strlen($x[3])).$x[4];'), '$CCNUMBER')

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.

Be aware that as of php5.4 you MUST NOT pass variables by reference, as in '[, int &$count ]' - if you do it will result in a fatal error. I think the writer is trying to say that the function accepts the parameter by reference, but that is not how it reads. -Manual needs updating/clarifying ?

This small class allows PHP users to read JSON files with include statements in them. For instance the include {{{ "relative/to/including.json" }}} is replaced by the content of the json file located at "relative/to/including.json".

also note that when you are using this functionality in a class and you need variables in that class, you can use a non static function as callback. array($this, functionName) should be enough to call an function of the class.

Either use create_function if you require the code only once, use a static class function if no need for accessing variables in that class. or use the array metioned earlier in my post for having access to class variables or other functions!

The pcre.backtrack_limit option (added in PHP 5.2) can trigger a NULL return, with no errors. The default pcre.backtrack_limit value is 100000. If you have a match that exceeds about half this limit it triggers a NULL response.e.g. My limit was at 100000 but 500500 triggered a NULL response. I'm not running unicode but I *guess* PCRE runs in utf-16.

Created this to fetch the link and name of an anchor tag. I use this when cleaning an HTML email to text. Using regex for HTML is not recommended but for this purpose I see no issue with it. This is not designed to work for nested anchors.

A note to keep in mind:I was primarily concerned with valid HTML so if attributes do no use ' or " to contain the values then this will need to be tweaked.If you can edit this to work better, please let me know.<?php/** * Replaces anchor tags with text * - Will search string and replace all anchor tags with text (case insensitive) * * How it works: * - Searches string for an anchor tag, checks to make sure it matches the criteria * Anchor search criteria: * - 1 - <a (must have the start of the anchor tag ) * - 2 - Can have any number of spaces or other attributes before and after the href attribute * - 3 - Must close the anchor tag * * - Once the check has passed it will then replace the anchor tag with the string replacement * - The string replacement can be customized * * Know issue: * - This will not work for anchors that do not use a ' or " to contain the attributes. * (i.e.- <a href=http: //php.net>PHP.net</a> will not be replaced) */function replaceAnchorsWithText($data) {/** * Had to modify $regex so it could post to the site... so I broke it into 6 parts. */$regex = '/(<a\s*'; // Start of anchor tag$regex .= '(.*?)\s*'; // Any attributes or spaces that may or may not exist$regex .= 'href=[\'"]+?\s*(?P<link>\S+)\s*[\'"]+?'; // Grab the link$regex .= '\s*(.*?)\s*>\s*'; // Any attributes or spaces that may or may not exist before closing tag $regex .= '(?P<name>\S+)'; // Grab the name$regex .= '\s*<\/a>)/i'; // Any number of spaces between the closing anchor tag (case insensitive)

if (is_array($data)) {// This is what will replace the link (modify to you liking)$data = "{$data['name']}({$data['link']})"; } return preg_replace_callback($regex, 'replaceAnchorsWithText', $data);}

echo replaceAnchorsWithText($input).'<hr/>';?>Will output:Test 1: PHP.NET1(http: //php.net1).Test 2: PHP.NET2(HTTP: //PHP.NET2).Test 3: php.net3 (is still an anchor)This last line had nothing to do with any of this

When you use preg_replace_callback in a class and have the callback function as a private method of that class, you need to set the callback function name like className::CallBack.
self::CallBack does not work and returns an error:
"Cannot call method self::CallBack() or method does not exist"!

For the callback I advise only to use a permanent or anonymous function.

Depending on the usage you may encounter memory issues when using create_function for the callback possibly due to attempts at being compatible with PHP 5.2 or prior. Some servers refuse to update their PHP for whatever reason.

Please peruse the create_function documentation for more details regarding its memory usage.

Don't use this function to fetch BBCode, as explained. If you have some text that runs over 5000 chars (average), it will run out of its limit and makes you download the PHP page.

According to this, you should instead use something more advanced yet complex. You will need a function called "str_replace_once()" (search for it), one called "countWord()", the famous "after()", "before()", "between()".

str_replace_once does same as str_replace, but only replace first occurence. As for countWord, I guess you know how to count the number of a word occurence. As for after, before and between, this is a function that you may find easily somewhere on the site by a user. Else, you can do it.

The following function is able to do all blocks, supposing [code] and [/code], you might wish things between parents dont get parsed, including [code] if inside of another [code].

$code returns the whole text semi-formated. You only need to use it as :
$code = prepareCode($code="Your text", $op="[tag]" , $end="[/tag]");
Then just replace the parent tags :
str_replace("[tag:0]", "<tag>", $code);
str_replace("[/tag:0]", "</tag>", $code);
So at the end something like :
[