peace_love
peace_love

Reputation: 6461

How can I parse a string with a precise string length?

I am parsing a text file that looks like this:

2.cat=262FU
2.dog=FSK4A

hier is the code:

if (false !== ($pos = strpos($line, '='))) {
            $prop=array();    
            $prop[trim(substr($line, 0, $pos))] = trim(substr($line, $pos + 1));
            $lineContArray = explode("=", $line);
            $identArray = explode(".", $lineContArray[0]);

            $ident = $identArray[0];
            $type = $identArray[1];     

            $value = $lineContArray[1];

            $found = 0;
            for ($i=0; $i<count($properties); $i++) {
                    if ($properties[$i]['number'] == $ident) {
                        $properties[$i][$type]= $value;
                        $found=1;
                        break;
                    }
            }

            if ($found == 0) { 
                if (!empty($type)) { 
                    $properties[] = array('number' => $ident, $type => $value); 
                } else { 
                   $properties[] = array($ident => $value); 
                } 
           }
 }

I want to insert the parsed content into the mysql database and check if the string length of cat is 5.

$sql = "INSERT INTO files (cat, dog) values(?,?) ";
$q = $pdo->prepare($sql);

foreach($properties as $row) {

            var_dump ($row['cat']);
            if (strlen($row['cat']) == 5){

            $q->execute(array($row['cat'], $row['dog'];
            }

            } else {                                
            echo "The length of cat is not 5";
           }
 }

I get the following error:

string(6) "262FU " 
The length of cat is not 5

But in my text file, there is no whitespace after 262FU. So what is the reason?

Upvotes: 2

Views: 73

Answers (2)

Paolo
Paolo

Reputation: 15827

You get $row from $properties

You set each element in $properties with a key-value pair array where for the key $type you use $value

the latter come from

$value = $lineContArray[1];

and going up again

$lineContArray = explode("=", $line);

It's likely that $line ends with a space or newline.

So I would trim $value

$value = trim($lineContArray[1]);

as you're already doing when you set $prop in the third line

Upvotes: 1

ogres
ogres

Reputation: 3690

First of all, make sure you are not counting and including the newline character at the end of the string , you can trim character to make sure you are not doing this , but I`d suggest 3 different approaches,

$fileContent = file_get_contents('file');
$contentLength = strlen($fileContent);


// Direct String parsing approach
function parseString1($string) {
    $result = Array();
    $tempId = '';
    $tempType = '';
    $tempValue = '';
    $step = 0;
    $stringLength = strlen($string);
    for($i = 0;$i < $stringLength;$i++) {
        $char = $string[$i];
        if($step == 0) {
            if($char != '.') {
                $tempId .= $char;
            } else {
                $step++;
            }
        } else if($step == 1) {
            if($char != '=') {
                $tempType .= $char;
            } else {
                $step++;
            }
        } else if($step == 2) {
            if(ctype_space($char)) {
                $result[] = Array( 'id' = $tempId, 'type' = $tempType, 'value' = $tempValue );
                $step = 0;
                $tempId = $tempType = $tempValue = '';
            } else {
                $tempValue .= $char;
            }
        }
    }

    if(!empty($tempId) && !empty($tempType) && !empty($tempValue)) {
        $result[] = Array( 'id' = $tempId, 'type' = $tempType, 'value' = $tempValue );      
    }


    return $result;
}

// Split string approach 
function parseString2($string) {
    $result = Array();
    $lines = split("\n", $string);
    foreach($lines as $line) {
        $parts = explode('=', $line);
        $value = trim($parts[1]);
        $parts = explode('.', $parts[0]);
        $id = $parts[0];
        $type = $parts[1];
        $result[] = Array( 'id' = $id, 'type' = $type, 'value' = $value );      
    }

    return $result;
}

// Regex whole string approach
function parseString3($string) {
    $result = Array();
    $pattern = '/(\d+).([^=]+)=(.*)\b/';
    $matchesCount = preg_match_all($pattern, $string, $matches);
    for($i = 0;$i < $matchesCount;$i++) {
        $result[] = Array( 'id' = $matches[1][$i], 'type' = $matches[2][$i], 'value' = $matches[3][$i] );       
    }

    return $result;
}

Upvotes: 1

Related Questions