Anagmate
Anagmate

Reputation: 1903

Mathematial operations in preg_match

I need to lower preg variable by one. Example:

$code = A4-7;
$new = preg_replace('/A([0-9])\-([0-9])/', 'S($1-1)-$2', $code);

I need to do something like that, so preg replace returns S3-7. Is there some way?

Upvotes: 0

Views: 50

Answers (2)

user1646111
user1646111

Reputation:

Try this (using preg_replace_callback)

$code = "A4-7";

function myfunc($matches)
{

  return 'S'.($matches[1]-1).'-'.$matches[2];
}
echo preg_replace_callback("#A(\d)-(\d)#","myfunc",$code);

Upvotes: 0

OdinX
OdinX

Reputation: 4211

You will have to extract the values first, perform the mathematical operations on the extracted values and then reconstruct the string to achieve what you want.

For example:

<?php
$code = 'A4-7';
preg_match('/A([0-9])\-([0-9])/', $code, $matches);
$new = 'S'.($matches[1]-1).'-'.$matches[2];
?>

Upvotes: 0

Related Questions