2011-10-07 13 views

cevap

3

$s = function ($vars) { 
    extract($vars); 
    return "$who likes $what"; 
}; 
echo $s(['who' => 'Tim', 'what' => 'King Pao']); // Tim likes King Pao 

Ve evet, PhpStorm şikayet ...:

tim likes kung pao 
6

Bunu yapmak için bir sürü yol olduğunu düşünüyorum ... ama bu akla geliyor.

$search = array('%who%', '%what_id%'); 
$replace = array('tim', 'kung pao'); 
$conference_target = str_replace(
    $search, 
    $replace, 
    "%who% likes %what%" 
); 

Ha, hatta vsprintf kullanarak çerçevesinde vardı:

sprintfn('second: %(second)s ; first: %(first)s', array(
    'first' => '1st', 
    'second'=> '2nd' 
)); 

: Bu the sprintf page Bu gibi aramalar için izin verir

geldi gibi görünüyor

class Helper_StringFormat { 

    public static function sprintf($format, array $args = array()) { 

     $arg_nums = array_slice(array_flip(array_keys(array(0 => 0) + $args)), 1); 

     for ($pos = 0; preg_match('/(?<=%)\(([a-zA-Z_]\w*)\)/', $format, $match, PREG_OFFSET_CAPTURE, $pos);) { 
      $arg_pos = $match[0][2]; 
      $arg_len = strlen($match[0][0]); 
      $arg_key = $match[1][0]; 

      if (! array_key_exists($arg_key, $arg_nums)) { 
       user_error("sprintfn(): Missing argument '${arg_key}'", E_USER_WARNING); 
       return false; 
      } 
      $format = substr_replace($format, $replace = $arg_nums[$arg_key] . '$', $arg_pos, $arg_len); 
      $pos = $arg_pos + strlen($replace); 
     } 

     return vsprintf($format, array_values($args)); 
    } 
} 

UPDATE
İşte ...

class Helper_StringFormat { 

    public static function sprintf($format, array $args = array()) { 
     $arg_nums = array_slice(array_flip(array_keys(array(0 => 0) + $args)), 1); 

     for ($pos = 0; preg_match('/(?<=%)\(([a-zA-Z_][\w\s]*)\)/', $format, $match, PREG_OFFSET_CAPTURE, $pos);) { 
      $arg_pos = $match[0][1]; 
      $arg_len = strlen($match[0][0]); 
      $arg_key = $match[1][0]; 

      if (! array_key_exists($arg_key, $arg_nums)) { 
       user_error("sprintfn(): Missing argument '${arg_key}'", E_USER_WARNING); 
       return false; 
      } 
      $format = substr_replace($format, $replace = $arg_nums[$arg_key] . '$', $arg_pos, $arg_len); 
      $pos = $arg_pos + strlen($replace); // skip to end of replacement for next iteration 
     } 

     return vsprintf($format, array_values($args)); 
    } 
} 

$str = "%(my var)s now work with a slight %(my var2)s"; 
$repl = array("my var" => "Spaces", "my var2" => "modification."); 

echo Helper_StringFormat::sprintf($str, $repl); 

ÇIKIŞ
Spaces şimdi ufak bir değişiklikle çalışmak olsa tam olarak test değil istediğini yapmak için bir güncelleme olduğunu.

+0

Bu hoş, çünkü bir '% (karakter) dizisinden kurtulmanın bir yolu yoktur. Eğer bunu düzeltmek için hiç tereddüt ettiysem, kodu bu ileti dizisine gönderirim – Casebash

+0

İkinci bağlantı adınızda BTW yazım hatası var. (Sprtinf) – peipst9lker

1

İstediğinizi yapmak için bir işlev yapıyorum. "quck-and-dirty" yaptım çünkü onu yeniden düzenlemek için fazla zamanım yok, belki onu githubuma yüklüyorum.

DÜZENLEME: bir hata düzeltme ...

[a-zA-Z0-9_] sadece olabilir

formattemplatter(
        '$who likes $what' 
        , array(
           'who' => 'Tim' 
          , 'what' => 'Kung Pao' 
        ) 
    ); 

Değişkenler gibi kullanın.

function formattemplater($string, $params) { 
    // Determine largest string 
    $largest = 0; 
    foreach(array_keys($params) as $k) { 
     if(($l=strlen($k)) > $largest) $largest=$l; 
    } 

    $buff = ''; 

    $cp  = false; // Conditional parenthesis 
    $ip  = false; // Inside parameter 
    $isp = false; // Is set parameter 

    $bl  = 1; // buffer length 
    $param = ''; // current parameter 

    $out = ''; // output string 
    $string .= '!'; 

    for($sc=0,$c=$oc='';isset($string{$sc});++$sc,++$bl) { 
     $c = $string{$sc}; 

     if($ip) { 
      $a = ord($c); 

      if(!($a == 95 || (     // underscore 
        ($a >= 48 && $a <= 57)  // 0-9 
        || ($a >= 65 && $a <= 90) // A-Z 
        || ($a >= 97 && $a <= 122) // a-z 
       ) 
      )) { 

       $isp = isset($params[$buff]); 

       if(!$cp && !$isp) { 
        trigger_error(
          sprintf(
            __FUNCTION__.': the parameter "%s" is not defined' 
            , $buff 
          ) 
          , E_USER_ERROR 
        ); 
       } elseif(!$cp || $isp) { 
        $out .= $params[$buff]; 
       } 

       $isp = $isp && !empty($params[$buff]); 
       $oc  = $buff = ''; 
       $bl  = 0; 
       $ip  = false; 
      } 
     } 

     if($cp && $c === ')') { 
      $out .= $buff; 

      $cp = $isp = false; 
      $c = $buff = ''; 
      $bl = 0; 
     } 

     if(($cp && $isp) || $ip) 
      $buff .= $c; 

     if($c === '$' && $oc !== '\\') { 
      if($oc === '(') $cp = true; 
      else $out .= $oc; 

      $ip = true; 
      $buff = $c = $oc = ''; 
      $bl = 0; 
     } 

     if(!$cp && $bl > $largest) { 
      $buff = substr($buff, - $largest); 
      $bl  = $largest; 
     } 

     if(!$ip && (!$cp || ($cp && $isp))) { 
      $out .= $oc; 
      if(!$cp) $oc = $c; 
     } 
    } 

    return $out; 
} 
0

başka daha basit bir yaklaşım bu olacaktır:

$template = '$who likes $what'; 

$vars = array(
    '$who' => 'tim', 
    '$what' => 'kung pao', 
); 

echo strtr($template, $vars); 

Çıkışlar: Ayrıca strtr kullanabilirsiniz

İlgili konular