Friday, April 28, 2017

str_repeat

<?php
    echo parenthesize('a == b ? c : (d == e ? x : y)');
    function parenthesize($expression) {
  $expression .= ';';
  $res = '';
  $depth = 0;
  for ($i = 0; $i < strlen($expression); ++$i) {
   $char = $expression[$i];
   switch ($char) {
    case '?':
     $res .= ' ? (';
     $depth++;
     break;
    case ':':
     $res .= ') : (';
     break;
    case ';':
     $res .= str_repeat(')', $depth) . ';';
     $depth= 0;
     break;
    default:
     $res .= $char;
   }
  }
  return rtrim($res, ';');
 }
?>
Output:
hello 
php
php
ello 

No comments:

Post a Comment

here docs

$x = <<<THE_END PHP stands for "PHP: Hypertext Preprocessor". The acronym "PHP" is therefore, usually referre...