-2

I try preg_replace_callback_array for math bbcode. Its returning as plain text while i require calculated result

<?php
$kode = array (
  "/\[math\]([0-9+\-\/*\)\(]+?)\[\/math\]/" =>
    function($matches) {$value = "$matches[1]"; return $value;},
);
$body = 'my result is [math]100-3[/math]';

echo preg_replace_callback_array($kode,$body);
?>

Bbcode work fine but doesn’t return calculation

If i use [math]100+10[/math] it return 100+10 but i want to get 110 here

Barmar
  • 741,623
  • 53
  • 500
  • 612
OH Pavel
  • 31
  • 6

3 Answers3

1

This is, in general, difficult. Your evaluation $value = "$matches[1]" would simply evaluate the string value. There is no simple function in PHP core library to convert a numerical calculation formula string into the result.

You may, however, learn to install chriskonnertz/string-calc with Composer and use it.

<?php

use ChrisKonnertz\StringCalc\StringCalc;

$kode = array (
  "/\[math\]([0-9+\-\/*\)\(]+?)\[\/math\]/" => function($matches) {
    $calc = new StringCalc();
    return $calc->calculate($matches[1]);
  },
);
$body = 'my result is [math]100-3[/math]';

echo preg_replace_callback_array($kode,$body);
?>
Koala Yeung
  • 7,475
  • 3
  • 30
  • 50
  • It was work without composar on 5.6 but on php 7 /e modifier not working $kode = array ( "/\[math\]([0-9+\-\/*\)\(]+?)\[\/math\]/e"=>'$1', ); $body = 'my result is [math]100-3[/math]'; echo preg_replace(array_keys($kode),array_values($kode),$body); – OH Pavel Mar 21 '19 at 08:03
  • Nice, I wasn't aware of that. +1. – Toto Mar 21 '19 at 10:08
  • The [PCRE modifier `e`](https://php.net/manual/en/reference.pcre.pattern.modifiers.php#reference.pcre.pattern.modifiers) was DEPRECATED in PHP 5.5.0, and REMOVED as of PHP 7.0.0. You simply cannot use it anymore in PHP 7+. – Koala Yeung Mar 22 '19 at 02:43
  • But that would be a neat trick for older versions of PHP. Didn't know about it. Thanks :-) – Koala Yeung Mar 22 '19 at 02:46
0

You can do it with eval(). This is normally a very dangerous function, but your pattern only matches simple numerical expressions, so it's safe here.

$kode = array (
  '/\[math\]([0-9+\-\/*)(]+?)\[\/math\]/' =>
    function($matches) {eval("\$value = $matches[1];"); return $value;},
);
Barmar
  • 741,623
  • 53
  • 500
  • 612
0

thanks everyone for reply i make it working like this

  $kode = array (
  "/\[math\]([0-9+\-\/*\)\(]+?)\[\/math\]/" =>
    function($matches) {$value = "$matches[1]"; return eval('return ' . $value . ';');},
);
$body = 'my result is [math]100-3[/math]';

echo preg_replace_callback_array($kode,$body);
OH Pavel
  • 31
  • 6