php 如何使用 preg_replace_callback?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11174807/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to use preg_replace_callback?
提问by Mark
I have the following HTML statement
我有以下 HTML 语句
[otsection]Wallpapers[/otsection]
WALLPAPERS GO HERE
[otsection]Videos[/otsection]
VIDEOS GO HERE
What I am trying to do is replace the [otsection] tags with an html div. The catch is I want to increment the id of the div from 1->2->3, etc..
我想要做的是用 html div 替换 [otsection] 标签。问题是我想将 div 的 id 从 1->2->3 等递增。
So for example, the above statement should be translated to
所以例如,上面的语句应该被翻译成
<div class="otsection" id="1">Wallpapers</div>
WALLPAPERS GO HERE
<div class="otsection" id="2">Videos</div>
VIDEOS GO HERE
As far as I can research, the best way to do this is via a preg_replace_callback to increment the id variable between each replacement. But after 1 hour of working on this, I just cant get it working.
据我所知,最好的方法是通过 preg_replace_callback 在每次替换之间增加 id 变量。但是经过 1 小时的工作后,我无法让它工作。
Any assistance with this would be much appreciated!
对此的任何帮助将不胜感激!
回答by Niet the Dark Absol
Use the following:
使用以下内容:
$out = preg_replace_callback(
"(\[otsection\](.*?)\[/otsection\])is",
function($m) {
static $id = 0;
$id++;
return "<div class=\"otsection\" id=\"ots".$id."\">".$m[1]."</div>";
},
$in);
In particular, note that I used a staticvariable. This variable persists across calls to the function, meaning that it will be incremented every time the function is called, which happens for each match.
特别要注意的是,我使用了一个static变量。这个变量在调用函数时持续存在,这意味着每次调用函数时它都会增加,每次匹配都会发生这种情况。
Also, note that I prepended otsto the ID. Element IDs should not start with numbers.
另外,请注意我ots在 ID前面加上了。元素 ID 不应以数字开头。
For PHP before 5.3:
对于 5.3 之前的 PHP:
$out = preg_replace_callback(
"(\[otsection\](.*?)\[/otsection\])is",
create_function('$m','
static $id = 0;
$id++;
return "<div class=\"otsection\" id=\"ots".$id."\">".$m[1]."</div>";
'),
$in);
回答by Amal Murali
Note: The following is intended to be a general answer and does not attempt to solve the OP's specific problem as it has already been addressed before.
What is preg_replace_callback()?
This function is used to perform a regular expression search-and-replace. It is similar to str_replace(), but instead of plain strings, it searches for a user-defined regex pattern, and then applies the callback function on the matched items. The function returns the modified string if matches are found, unmodified string otherwise.
此函数用于执行正则表达式搜索和替换。它类似于str_replace(),但不是纯字符串,而是搜索用户定义的正则表达式模式,然后在匹配的项目上应用回调函数。如果找到匹配项,该函数返回修改后的字符串,否则返回未修改的字符串。
When should I use it?
我应该什么时候使用它?
preg_replace_callback()is very similar to preg_replace()- the only difference is that instead of specifying a replacement string for the second parameter, you specify a callbackfunction.
preg_replace_callback()非常类似于preg_replace()- 唯一的区别是不是为第二个参数指定替换字符串,而是指定一个callback函数。
Use preg_replace()when you want to do a simple regex search and replace. Use preg_replace_callback()when you want to do more than just replace. See the example below for understanding how it works.
使用preg_replace()时,你想要做一个简单的正则表达式搜索和替换。使用preg_replace_callback()时,你想要做的不仅仅是更换。请参阅下面的示例以了解其工作原理。
How to use it?
如何使用它?
Here's an example to illustrate the usage of the function. Here, we are trying to convert a date string from YYYY-MM-DDformat to DD-MM-YYYY.
下面是一个例子来说明该函数的用法。在这里,我们试图将日期字符串从YYYY-MM-DD格式转换为DD-MM-YYYY.
// our date string
$string = '2014-02-22';
// search pattern
$pattern = '~(\d{4})-(\d{2})-(\d{2})~';
// the function call
$result = preg_replace_callback($pattern, 'callback', $string);
// the callback function
function callback ($matches) {
print_r($matches);
return $matches[3].'-'.$matches[2].'-'.$matches[1];
}
echo $result;
Here, our regular expression pattern searches for a date string of the format NNNN-NN-NNwhere Ncould be a digit ranging from 0- 9(\dis a shorthand representation for the character class [0-9]). The callback function will be called and passed an array of matched elements in the given string.
在这里,我们的正则表达式模式搜索格式的日期字符串,NNNN-NN-NN其中N可以是范围从0- 9(\d是字符类的速记表示[0-9]) 的数字。回调函数将被调用并传递给定字符串中匹配元素的数组。
The final result will be:
最终结果将是:
22-02-2014
Note:The above example is for illustration purposes only. You should notuse to parse dates. Use DateTime::createFromFormat()and DateTime::format()instead. This questionhas more details.
注意:以上示例仅用于说明目的。你不应该用来解析日期。使用DateTime::createFromFormat()和DateTime::format()代替。这个问题有更多细节。

