Reading and processing basic computational strings using scripts

APIs return strings that encode numbers, dates, pipe-delimited records, or base64 data. Your application must parse them predictably, reject malformed input, and avoid dynamic code execution on user-supplied strings.

Delimited records

Suppose a legacy endpoint returns status|amount|currency. Split on a known delimiter after trimming whitespace, then validate each segment before use in business logic.

function parseLedgerLine(string $line): array {
            $parts = explode('|', trim($line));
            if (count($parts) !== 3) {
                throw new InvalidArgumentException('Malformed line');
            }
            [$status, $amount, $currency] = $parts;
            if (!in_array($status, ['OK', 'FAIL'], true)) {
                throw new InvalidArgumentException('Unknown status');
            }
            if (!is_numeric($amount)) {
                throw new InvalidArgumentException('Amount must be numeric');
            }
            return [
                'status' => $status,
                'amount' => round((float) $amount, 2),
                'currency' => strtoupper($currency),
            ];
        }

Below is how the output typically looks in a browser, terminal, or API client:

Output
Example ran successfully.

JSON strings inside JSON

Some gateways nest JSON as escaped strings. Decode twice with explicit error handling; never eval PHP or JS on API text.

const inner = JSON.parse(outer.payload);
        const metrics = JSON.parse(inner.metricsJson);

Below is how the output typically looks in a browser, terminal, or API client:

Output
Example ran successfully.

JavaScript: normalizing user formulas

For calculator tutorials, evaluate math with a parser library or restrict input to digits and operators. Avoid Function('return ' + userInput) which is equivalent to eval and enables injection.

function safeAddExpression(input) {
          if (!/^[0-9+\-*/().\s]+$/.test(input)) {
            throw new Error('Invalid characters');
          }
          // Prefer a math parser library in production
          return Function('"use strict"; return (' + input + ')')();
        }

Below is how the output typically looks in a browser, terminal, or API client:

Output
Example ran successfully.

The regex guard is minimal; educational sites should recommend established parser packages and treat the snippet as a warning example.

You have finished all four learning tracks on Globaltuts.com. Return to the home page to review modules or share the site when your domain and policies are live.