preg_replace将匹配的次数传递给第二个参数

时间:2014-08-19 13:50:30

标签: php regex preg-replace preg-match

在PHP中使用preg_replace时,是否可以获取匹配数并将其传递给preg_replace的第二个参数。

我正在尝试做的例子:

$str = <<<EOF
*Samsung
This is the description text for Samsung
**Early years
Korean town
***Founders
EOF;

echo preg_replace('/(?m)^\*{1,3}([^*].*)$/', '<h {} >$1</h {}>', $str);
//Note the {} in the above. That's where the count from the regex needs to go. So we'll be create H tags based on the replacements.

所以最终输出将是:

<h1>Samsung</h1> // There was one `*` here
This is the description text for Samsung
<h2>Early years</h2> // There were two `*`s here
Korean town
<h3>Founders</h3> // There were three `*`s here

这样的事情可能吗?可以从正则表达式中提取计数吗?

2 个答案:

答案 0 :(得分:3)

如建议使用回调来执行此操作。你可以根据自己的需要调整它......

$str = preg_replace_callback('~(?m)^(\*{1,3})([^*].*)$~', 
     function($m) {
         $count = strlen($m[1]);
         return "<h$count>$m[2]</h$count>";
     }, $str);

答案 1 :(得分:0)

TRY

$str = <<<EOF
*Samsung
This is the description text for Samsung
**Early years
Korean town
***Founders
EOF;
function turnStarToHeader($m) {
    static $id = 0;
    $id++;
    return "<h$id>$m[1]</h$id>";
 }

echo preg_replace_callback('/(?m)^\*{1,3}([^*].*)$/', 'turnStarToHeader', $str);