2012-06-07 2 views
3

상황은 간단합니다 :PHP에서 JavaScript로 새 줄 바꾸기

일반 텍스트 형식의 일반 HTML 양식을 게시합니다. 그런 다음 PHP에서 양식의 내용에 따라 JavaScript 함수를 등록합니다.

다음 코드를 사용하여 수행됩니다 : 마법처럼

$js = sprintf("window.parent.doSomething('%s');", $this->textarea->getValue()); 

작품을, 내가 줄 바꿈을 처리하기 위해 시도 할 때까지. 개 글자를 char 13으로 대체해야하지만 (실제로 믿습니다), 작동하는 해결책은 없습니다. 나는 시도 다음

$js = sprintf("window.parent.doSomething('%s');", "'+String.fromCharCode(13)+'", $this->textarea->getValue()); 

사람이 내가이 줄 바꿈을 올바르게 처리 할 수있는 방법에 대한 단서를 가지고 있는가 다음

$textarea = str_replace("\n", chr(13), $this->textarea->getValue()); 

그리고를? 이 문자와 문자열에 모든 새로운 라인을 교체해야

str_replace(array("\n\r", "\n", "\r"), char(13), $this->textarea->getValue()); 

사용 (13)

+0

올바른 방법입니다. 하지만 다른 문자를 추가하여 텍스트 필드 검사를 완료 할 수 있습니다 – luther

+1

왜 '\ n'을 바꾸시겠습니까? 목표를 지정할 수 있습니까? – nebulousGirl

+1

'$ this-> textarea-> getValue());'가'''포함되어 있으면 실패합니다. – Eric

답변

3

거의 대부분의 경우 줄 바꿈을 실제로 바꾸는 것을 잊었습니다.

이 트릭을 수행해야합니다

우리 WebApplication.php 파일에서

을 찍은 문제는 이미 우리의 코드베이스의 다른 곳에서 해결 된

$js = sprintf("window.parent.doSomething('%s');" 
    , preg_replace(
       '#\r?\n#' 
      , '" + String.fromCharCode(13) + "' 
      , $this->textarea->getValue() 
); 
-1

했다 :

str_replace("\n", '\n', $this->textarea->getValue()); 

이 모든 새로운 라인 문자를 교체 리터럴 문자열 '\n'


그러나, 당신은 JSON으로 인코딩 잘 할 것 :뿐만 아니라 따옴표가 해결됩니다

$js = sprintf(
    "window.parent.doSomething('%s');", 
    json_encode($this->textarea->getValue()) 
); 

합니다.

+0

** - 1 ** - 작동하지 않습니다. 왜냐하면' "\ n"== char (13)' – Eric

1

은 당신이해야 할 무엇을 의미

1

... :

/** 
    * Log a message to the javascript console 
    * 
    * @param $msg 
    */ 
    public function logToConsole($msg) 
    { 
     if (defined('CONSOLE_LOGGING_ENABLED') && CONSOLE_LOGGING_ENABLED) 
     { 
      static $last = null; 
      static $first = null; 
      static $inGroup = false; 
      static $count = 0; 

      $decimals = 5; 

      if ($first == null) 
      { 
       $first   = microtime(true); 
       $timeSinceFirst = str_repeat(' ', $decimals) . ' 0'; 
      } 

      $timeSinceFirst = !isset($timeSinceFirst) 
       ? number_format(microtime(true) - $first, $decimals, '.', ' ') 
       : $timeSinceFirst; 

      $timeSinceLast = $last === null 
       ? str_repeat(' ', $decimals) . ' 0' 
       : number_format(microtime(true) - $last, $decimals, '.', ' '); 

      $args = func_get_args(); 
      if (count($args) > 1) 
      { 
       $msg = call_user_func_array('sprintf', $args); 
      } 
      $this->registerStartupScript(
       sprintf("console.log('%s');", 
        sprintf('[%s][%s] ', $timeSinceFirst, $timeSinceLast) . 
        str_replace("\n", "'+String.fromCharCode(13)+'", addslashes($msg)))); 

      $last = microtime(true); 
     } 
    } 

당신이 관심있는 비트는 :

str_replace("\n", "'+String.fromCharCode(13)+'", addslashes($msg)) 

질문에 'sprintf, str_replace ...을 잊어 버렸습니다.