gyogyo0101
gyogyo0101

Reputation: 61

How do I use a part of preg_replace pattern as a variable?

function anchor($text)
{
 return preg_replace('#\&gt;\&gt;([0-9]+)#','<span class=anchor><a href="#$1">>>$1</a></span>', $text);
}

This piece of code is used to render page anchor. I need to use the

([0-9]+)

part as a variable to do some maths to define the exact url for the href tag. Thanks.

Upvotes: 0

Views: 276

Answers (1)

Braiba
Braiba

Reputation: 571

Use preg_replace_callback instead.

In php 5.3 +:

$matches = array();
$text = preg_replace_callback(
  $pattern,
  function($match) use (&$matches){
    $matches[] = $match[1];
    return '<span class=anchor><a href="#$1">'.$match[1].'</span>';
  }
);

In php <5.3 :

global $matches;
$matches = array();
$text = preg_replace_callback(
  $pattern,
  create_function('$match','global $matches; $matches[] = $match[1]; return \'<span class=anchor><a href="#$1">\'.$match[1].\'</span>\';')
);

Upvotes: 1

Related Questions