A fixed number variable multifly a relative number in a string

$fixNum=30;

I have a fixed number variable like the above.
and a string variable like the below.

$myVar='Hello, relativeNum250 I am a boy and relativeNum300 you are a girl';
The 1st relativeNum250 means 7500 which is 30($fixNum)*250.
The 2nd relativeNum300 means 9000 which is 30($fixNum)*300.

So in order to produce, the code below works fine…

$myVar=str_replace('relativeNum250', $fixNum*250, $myVar); $myVar=str_replace('relativeNum300', $fixNum*300, $myVar); echo $myVar;
The result of the code above is the following which is my target result.

Hello, 7500 I am a boy and 9000 you are a girl

As the variable $myVar is dynamic, it can be varied like the code below.

[code]$myVar=‘You are a relativeNum100 woman, I am a relativeNum120 man and they are relativeNum360 people’;

$myVar=str_replace(‘relativeNum100’, $fixNum100, $myVar);
$myVar=str_replace(‘relativeNum120’, $fixNum
120, $myVar);
$myVar=str_replace(‘relativeNum360’, $fixNum*360, $myVar);
[/code]The result of the code above is the following which is my target result.

You are a 3000 woman, I am a 3600 man and they are 10800 people

I don’t know how many relativeNum is in the string and what is the value of each relativeNum,i.e 100,120,360.
but I know only ‘fixNum=30’ and 3 digit number is followed by each relativeNum.
And I have to find the value of each relativeNum by multifling 30($fixNum)" and the 3 digit which is followed by 'relativeNum.

Can I produce my target result with the dynamic string($myVar) by your help?

You could write a function that searches your string for relativeNum, then checks that the next three characters are numeric, extracts the three digits, performs the calculation, then substitutes the result back into the string.

Much as I try to not use them, I suspect it might be something you could do with a regular expression, searching for a fixed string (relativeNum) followed by exactly three numeric digits.

1 Like

Whoops, please ignore my previous post because it is incorrect, I was in a hurry to go for lunch.

Please try this instead:

<?php 
declare(strict_types=1);
ini_set('display_errors', 'true');
error_reporting(-1);

//==================================
function fnReplace( $myVar, $fixNum)
{
  $aRelNums =
  [
    'relativeNum100',
    'relativeNum120',
    'relativeNum360', 
  ];

  $afixNums = 
  [
    $fixNum * 100,
    $fixNum * 120,
    $fixNum * 360,
  ];

  $result = str_replace($aRelNums, $afixNums, $myVar);

  return $result;
}

$fixNum = 30;
$myVar  = 'You are a relativeNum100 woman,  I am a relativeNum120 man and they are relativeNum360 people';

echo fnReplace( $myVar, $fixNum);

// $result:
//   'You are a 3000 woman, I am a 3600 man and they are 10800 people

Without regex, I was thinking

function fnReplace($myString, $myNum) { 
  $tempString = $myString;
  $found = strpos($tempString, "relativeNum"); 
  while ($found !== false) { 
    // grab next three characters starting at $found + len("relativeNum")
    // or perhaps search for the next space after $found, to allow different number lengths
    // check they are numeric, if they are
    // multiply them by $myNum
    // join the part of the string < $found, the result, and the end of the string after the numbers
    $found = strpos($tempString, "relativeNum"); // to find the next one
    } // end of while loop
  return $tempstring; 
  } // end of function

(I’ve done it as pseudo-code as I don’t have access to a server at the moment)

(ETA - anyone else frustrated that every time I type “strpos” the editor changes it to “strops” ?)

(EATA - did I read about some kind of “eval” function that could be used for stuff like this, but with a warning about it being bad in some way?)

User Contributed Notes [226] from the PHP Manual

Kepp the following Quote in mind:

If eval() is the answer, you’re almost certainly asking the
wrong question. – Rasmus Lerdorf, BDFL of PHP

Thanks for your help, John_Betong.
As I apply your code, it produces an error saying like the follow

Parse error: syntax error, unexpected '[' in relativeNum.php on line 10

line09 $aRelNums = line10 [ line11 'relativeNum100',how can I fix “[” in line10 above?

Unfortunately there is no syntax error using PHP 7 :slight_smile:

The square brackets are the shorthand code for the old array(…); function.

Try this:


$aRelNums = array(
'relativeNum100',
'relativeNum120',
'relativeNum360', 
);

Edit:
Remove linefeeds if the script still produce errors.

What version of PHP are you using?

I am using the version belowPHP Version 5.2.12
I am afraid that since the code above is not dynamic in relativeNum.

I do not understand why the script is not dynamic.

Did you remove “Remove linefeeds if the script still produce errors?”

$aRelNums = array( 'relativeNum100', 'relativeNum120', 'relativeNum360'  );

Okay, John_Betong. Here is my test of your code.

<?php 2 3 4 declare(strict_types=1); 5 ini_set('display_errors', 'true'); 6 error_reporting(-1); 7 8 //================================== 9 function fnReplace( $myVar, $fixNum) 10 { 11 12 $aRelNums = array( 13 'relativeNum100', 14 'relativeNum120', 15 'relativeNum360', 16 ); 17 18 19 $aRelNums = array( 20 'relativeNum100', 21 'relativeNum120', 22 'relativeNum360', 23 ); 24 25 26 $afixNums = array( 27 $fixNum * 100, 28 $fixNum * 120, 29 $fixNum * 360, 30 ); 31 32 $result = str_replace($aRelNums, $afixNums, $myVar); 33 34 return $result; 35 } 36 37 $fixNum = 30; 38 $myVar = 'You are a relativeNum100 woman, I am a relativeNum120 man and they are relativeNum360 people'; 39 40 echo fnReplace( $myVar, $fixNum); 41 42 43 44 45 46 ?> The code above produces the following. it is correct and it is my target result.

You are a 3000 woman, I am a 3600 man and they are 10800 people

So far so good.

However, if $myVar is like the following

$myVar='Hello, relativeNum250 I am a boy and relativeNum300 you are a girl';I have to add the code below.

19 $aRelNums = array( 20 'relativeNum250', 21 'relativeNum300', 23 ); 24 25 26 $afixNums = array( 27 $fixNum * 250, 28 $fixNum * 300, 30 );Since the relativeNum is so dynamic, I think and afraid that I cannot add all numbers from 100 to 999 into the array.

I missed this your point in the first post:

“I don’t know how many relativeNum is in the string and what is the value of each relativeNum,i.e 100,120,360.”

@droopsnoot’s solution should be OK; which I briefly tried. There is a lot of string manipulation to code before it will work.

I will think about a solution.

Why not try using range() ?

@joon1, @droopsnoot

Success :slight_smile:

<?php 
declare(strict_types=1);
ini_set('display_errors', 'true');
error_reporting(-1);


//==================================
function fnStrPos( $subject='')
// :array // PHP7 ONLY
{
  $aBodies = array(' woman,', ' man', ' people');
  foreach($aBodies as $id => $body):
    $pos      = strpos($subject, $body);
    $result[] = substr($subject, $pos -3, 3);
  endforeach;  

  return $result;
}

// SET VALUES
  $aRange = range(1, 88, 11);

  $myVar  = <<< ____TMP
    You are a    relativeNum200 woman,
    I am a       relativeNum301 man
    and they are relativeNum404 people
____TMP;

  $aVar   = fnStrPos($myVar);

  echo '<br>ORIGINAL ==> '.$myVar .'<br>';
  foreach( $aRange as $id => $fixNum):
    // RESET $subject EVERY LOOP
    $subject = $myVar;
    for($i2=0; $i2<3; $i2++):
      $search   ='relativeNum' .$aVar[$i2];
      $replace  = $fixNum * (int)$aVar[$i2];
      $replace  = number_format( (float) $replace);
      $replace  = '<b>' .$replace .'</b>';
      $subject  = str_replace($search, $replace, $subject);
    endfor;  
    echo '<br>$fixNum  ==> ' .$fixNum;
    echo '<br>$subject ==> ' .$subject .'<br>';
  endforeach;  

**Output:** ```

ORIGINAL ==> You are a relativeNum200 woman, I am a relativeNum301 man and they are relativeNum404 people

$fixNum ==> 1
$subject ==> You are a 200 woman, I am a 301 man and they are 404 people

$fixNum ==> 12
$subject ==> You are a 2,400 woman, I am a 3,612 man and they are 4,848 people

$fixNum ==> 23
$subject ==> You are a 4,600 woman, I am a 6,923 man and they are 9,292 people

$fixNum ==> 34
$subject ==> You are a 6,800 woman, I am a 10,234 man and they are 13,736 people

$fixNum ==> 45
$subject ==> You are a 9,000 woman, I am a 13,545 man and they are 18,180 people

$fixNum ==> 56
$subject ==> You are a 11,200 woman, I am a 16,856 man and they are 22,624 people

$fixNum ==> 67
$subject ==> You are a 13,400 woman, I am a 20,167 man and they are 27,068 people

$fixNum ==> 78
$subject ==> You are a 15,600 woman, I am a 23,478 man and they are 31,512 people

1 Like

Thank you, John_Betong for your deep concerning.
Your code works fine.

However, in case of $myVar=‘Hello, relativeNum250 I am a boy and relativeNum300 you are a girl’ which is on my 1st question, it, I am so afraid, will not work.

Try adding " I am a boy" and " you are a girl" to the array in the function.

Be careful of the leading space and capitalisation.

It should work ok.

Are there any more conditions to satisfy?

Edit:
Amended the boy and girl.

Also add an if condition before adding to the array to ensure the value is positivel

[quote=“John_Betong, post:16, topic:287725”]
Are there any more conditions to satisfy?
[/quote]Yes, I am afraid and still hungry.

$myVar can be like the following because $myVar itself is a variable and dynamic.

$myVar='Be relativeNum210 careful of the leading relativeNum350 space and capitalisation';

My target result will be like the following.

Be 6300 careful of the leading 10500 space and capitalisation

In order to get my target result above, I should add, in my think, not only ‘boy’ and ‘girl’ but also ‘careful’ and ‘space’ like the following.

$aBodies = array(' woman,', ' man', ' people', 'boy', 'girl'. 'careful', 'space');

I cannot list most of the words in the webster dictionary in the array.

Back to my original question. I think $myVar can be like the following.

$myVar='Hello, relativeNum_open250relativeNum_close I am a boy and relativeNum_open300relativeNum_close you are a girl';

I like to get my target result below with changing the number which has always 3 digits(100~999) between relativeNum_open and relativeNum_close to multiply by fixNum.

Hello, 7500 I am a boy and 9000 you are a girl

OK, I have written another function

Notes:

  1. the function has each echoed variable remmed which should be unremmed (by removing the leading // ) to display the variables.
  2. the function only removes a single $search string but also tests if there are any more $search strings to replace. If there are then the function calls itself with a new $result.
  3. hopefully the script will be studied rather than just copied and pasted :slight_smile:

Version: 003:

<?php 
  declare(strict_types=1); // PHP7 ONLY
  ini_set('display_errors', 'true');
  error_reporting(-1);

# SET VARIABLES and TEST DATA
  $fixNum = 9;
  $search = 'relativeNum'; 
  $spacer = '&nbsp;&nbsp;&nbsp;&nbsp;'; 
  $aTests = array(
    'This is a relativeNum200 TEST to see relativeNum310 if it relativeNum404 works',
    'relativeNum200 WORKS even if relativeNum310 is the FIRST relativeNum404 Number or even the last relativeNum500',
    'Happiness is a relativeNum111 string which is relativeNum420 converted every relativeNum888 time.' ,
    'Hello, relativeNum250 I am a boy and relativeNum300 you are a girl' ,
    'Be relativeNum210 careful of the leading relativeNum350 space and capitalisation' ,
     'You are a    relativeNum200 woman,  I am a       relativeNum301 man  and they are relativeNum404 people' ,
  );  // end $aTests array()

# CONVERT and DISPLAY
    echo '<b> $fixNum : </b> '  ,$fixNum ; 
    echo '<hr>';          

    foreach( $aTests as $id => $myVar):
      echo  '<b> $myVar : </b> <br> ' 
            . $spacer 
            . '<i style="font-size:small;">' .$myVar .'</i>';
      
      echo  '<br> <b> $result : </b> <br>' 
            . $spacer
            . fnConversion($myVar, $search, $fixNum);

      echo '<br> <hr>';
    endforeach;  

//===============================================
function fnConversion( $subject, $search, $fixNum)
: string //  PHP7 ONLY
{
  $result = NULL; // default return value

   // echo '<br> $iLen ==> ',
    $iLen = strlen( $search );

  // echo '<br> $iPos ==> ',
    $iPos = strpos($subject, $search);  

  // echo '<br> $start ==> ',
    $start = substr($subject, 0, $iPos);  

  // echo '<br> $finish ==> ',
    $finish = substr($subject, (int) $iPos + $iLen + 3);  

  // echo '<br> $iNum ==> ',
    $iNum = substr($subject, $iPos + $iLen, 3);  

  // echo '<br> $iCalc ==> ',
    $iCalc = $fixNum * $iNum;  

  // echo '<br> $result ==> ',
    $result = $start . $iCalc . $finish; 

  if( strpos($result, $search) ):
    // echo '<br> AGAIN with a NEW $result : ' . $result;
    $result = fnConversion( $result, $search, $fixNum);
  endif;
    
  return $result;
}//==============================================

Output:

$fixNum : 9 

$myVar :
    This is a relativeNum200 TEST to see relativeNum310 if it relativeNum404 works
$result :
    This is a 1800 TEST to see 2790 if it 3636 works
$myVar :
    relativeNum200 WORKS even if relativeNum310 is the FIRST relativeNum404 Number or even the last relativeNum500
$result :
    1800 WORKS even if 2790 is the FIRST 3636 Number or even the last 4500
$myVar :
    Happiness is a relativeNum111 string which is relativeNum420 converted every relativeNum888 time.
$result :
    Happiness is a 999 string which is 3780 converted every 7992 time.
$myVar :
    Hello, relativeNum250 I am a boy and relativeNum300 you are a girl
$result :
    Hello, 2250 I am a boy and 2700 you are a girl
$myVar :
    Be relativeNum210 careful of the leading relativeNum350 space and capitalisation
$result :
    Be 1890 careful of the leading 3150 space and capitalisation
$myVar :
    You are a relativeNum200 woman, I am a relativeNum301 man and they are relativeNum404 people
$result :
    You are a 1800 woman, I am a 2709 man and they are 3636 people

Are there any more conditions to satisfy?

Edit:
The editor went berserk when copying and pasting :frowning:
I had to make numerous small changes to the script and the output :slight_smile:

1<?php 2 declare(strict_types=1); // PHP7 ONLY 3 ini_set('display_errors', 'true'); 4 error_reporting(-1); 5 6 # SET VARIABLES and TEST DATA 7 $fixNum = 9; 8 $search = 'relativeNum'; 9 $spacer = ' '; 10 $aTests = array( 11 'This is a relativeNum200 TEST to see relativeNum310 if it relativeNum404 works', 12 'relativeNum200 WORKS even if relativeNum310 is the FIRST relativeNum404 Number or even the last relativeNum500', 13 'Happiness is a relativeNum111 string which is relativeNum420 converted every relativeNum888 time.' , 14 'Hello, relativeNum250 I am a boy and relativeNum300 you are a girl' , 15 'Be relativeNum210 careful of the leading relativeNum350 space and capitalisation' , 16 'You are a relativeNum200 woman, I am a relativeNum301 man and they are relativeNum404 people' , 17 ); // end $aTests array() 18 19 # CONVERT and DISPLAY 20 echo '<b> $fixNum : </b> ' ,$fixNum ; 21 echo '<hr>'; 22 23 foreach( $aTests as $id => $myVar): 24 echo '<b> $myVar : </b> <br> ' 25 . $spacer 26 . '<i style="font-size:small;">' .$myVar .'</i>'; 27 28 echo '<br> <b> $result : </b> <br>' 29 . $spacer 30 . fnConversion($myVar, $search, $fixNum); 31 32 echo '<br> <hr>'; 33 endforeach; 34 35 //=============================================== 36 function fnConversion( $subject, $search, $fixNum) 37 : string // PHP7 ONLY 38 { 39 $result = NULL; // default return value 40 41 // echo '<br> $iLen ==> ', 42 $iLen = strlen( $search ); 43 44 // echo '<br> $iPos ==> ', 45 $iPos = strpos($subject, $search); 46 47 // echo '<br> $start ==> ', 48 $start = substr($subject, 0, $iPos); 49 50 // echo '<br> $finish ==> ', 51 $finish = substr($subject, (int) $iPos + $iLen + 3); 52 53 // echo '<br> $iNum ==> ', 54 $iNum = substr($subject, $iPos + $iLen, 3); 55 56 // echo '<br> $iCalc ==> ', 57 $iCalc = $fixNum * $iNum; 58 59 // echo '<br> $result ==> ', 60 $result = $start . $iCalc . $finish; 61 62 if( strpos($result, $search) ): 63 // echo '<br> AGAIN with a NEW $result : ' . $result; 64 $result = fnConversion( $result, $search, $fixNum); 65 endif; 66 67 return $result; 68 }//============================================== 69 ?>I don’t understand your code fully, So I write the code above by copying your code.

It says the following.

Parse error: syntax error, unexpected ':', expecting '{' in test.php on line 37

Whoops. Rem line 37 because it is for PHP 7 only and it should work ok.

I know is is Saturday, hope someone else has time to try the script?

Thank you, John_Betong
I hope you enjoy your weekend.
I will wait Monday and enjoy my weekend.