Get value by sweeping PHP string

Tags: ,



I have the following value in a variable:

$var = M000000017590;

obtained from:

$DATO  = "P000001759000_M000000017590_MSG1TRANSACCIONEXITOSA _MSG2 CONMILLA,"; 
$porciones = explode("_", $DATO);
$var = $porciones[2];

I need to start sweeping from left to right and when I find the first non-zero number that from there saves the value in a variable, for example: M000000017590 = 17590 A str_replace does not help me and replacing the 0 with "" since inside the last string it can also contain 0, some help?

Answer

In PHP strings are byte arrays, you can leverage on that

<?php

$DATO  = "P000001759000_M000000017590_MSG1TRANSACCIONEXITOSA _MSG2 CONMILLA,"; 

$num_detected = false;

$buffer = '';

for($i=0; $i<strlen($DATO); $i++)
{        
    //start
    if( intval($DATO[$i]) > 0 )
        $num_detected = true;
    
    //middle
    if($num_detected)
        $buffer .=$DATO[$i];
    
    //stop
    if($num_detected && !intval($DATO[$i]))
        break;
}

echo $buffer;

?> 

You start reading chars from your string one-by-one and check whether its numeric value holds for you or not. So as soon as you find a desired value(non-zero in your case) you start accumulating from thereon until you encounter an undesired value (zero/alpha in your case)

UPDATE: As mentioned by @waterloomatt if there are zeros embedded inside a valid sequence then the above algorithm fails. To fix this try

<?php
 
 function checkAhead($DATO, $i){
      
    if(!isset($DATO[$i++]))
        return false;
      
      if(is_numeric($DATO[$i++]))
          return true;
      else
          return false;
}

$DATO  = "P0000017590040034340_M000000017590_MSG1TRANSACCIONEXITOSA _MSG2 CONMILLA,"; 

$num_detected = false;

$buffer = '';

for($i=0; $i<strlen($DATO); $i++)
{        
    //start
    if( intval($DATO[$i]) > 0 )
        $num_detected = true;
    
    //middle
    if($num_detected)
        $buffer .=$DATO[$i];
    
    //stop
    if($num_detected && ( !checkAhead($DATO, $i)  ))
        break;
}

echo $buffer;

?>


Source: stackoverflow