Click here to Skip to main content
15,886,199 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Hello ,i tried to use this code to replace any __Random_and[x,y] with rand(x,y) but it didn't run please help me 


PHP
function charCallbackRand($matches1){
    $charOne = (int)$matches1[1];
    $charTwo = (int)$matches1[2];
    return rand($charOne,$charTwo);
    }
    $myword = __Random_and[22,95];
    $result = preg_replace_callback('/__Random_anm\[(\d+),(\d+)\]/', 'charCallbackRand', $myword);


What I have tried:

PHP
function charCallbackRand($matches1){
    $charOne = (int)$matches1[1];
    $charTwo = (int)$matches1[2];
    return rand($charOne,$charTwo);
    }
    $myword = __Random_and[22,95];
    $result = preg_replace_callback('/__Random_anm\[(\d+),(\d+)\]/', 'charCallbackRand', $myword);
Posted
Updated 17-May-16 19:00pm
Comments
Patrice T 17-May-16 21:08pm    
define 'didn't run'

Instead of using a preg_replace_callback() you can directly insert the wanted numbers from the original text with preg_replace()

Try this:
PHP
$string = '__Random_and[22,95]';
$pattern = '/__Random_and\[(\d+),(\d+)\]';
$replacement = 'rand($1,$2)';
$result preg_replace($pattern, $replacement, $string);
 
Share this answer
 
RegEx only apply on strings, not on code.
PHP
function charCallbackRand($matches1){
    $charOne = (int)$matches1[1];
    $charTwo = (int)$matches1[2];
    return 'rand('.$charOne.','.$charTwo.')';
    }
    $myword = '__Random_and[22,95]';
    $result = preg_replace_callback('/__Random_anm\[(\d+),(\d+)\]/', 'charCallbackRand', $myword);

Your code is way complicated for doing such a simple thing, see Solution 1.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900