백엔드 개발 PHP 튜토리얼 js 파일을 자동으로 압축하는 데 사용되는 PHP 코드

js 파일을 자동으로 압축하는 데 사용되는 PHP 코드

Jul 25, 2016 am 09:02 AM

  1. /* 2008년 4월 9일. 버전 1.1
  2. *
  3. * 이것은 Dean Edwards JavaScript Packer의 PHP 버전입니다.
  4. * 기반 :
  5. *
  6. * ParseMaster, 버전 1.0.2(2005-08-19) Copyright 2005, Dean Edwards
  7. * 다중 패턴 파서.
  8. * 알려진 버그: escapeChar를 대체품으로 사용할 때 잘못된 동작
  9. * 함수인 값
  10. *
  11. * packer, 버전 2.0.2(2005-08-19) Copyright 2004-2005, Dean Edwards
  12. *
  13. * 라이센스: http://creativecommons.org/licenses/LGPL/2.1/
  14. *
  15. * Nicolas Martin이 PHP로 포팅했습니다.
  16. *
  17. * ----------------------------- ---------------
  18. * 변경 로그:
  19. * 1.1 : 버그 수정, '/0' 압축 후 압축을 풀면 '/'가 됩니다.
  20. * --------------------------------- -----------
  21. *
  22. * 사용 예 :
  23. * $myPacker = new JavaScriptPacker($script, 62 , 참, 거짓);
  24. * $packed = $myPacker->pack();
  25. *
  26. * 또는
  27. *
  28. * $myPacker = new JavaScriptPacker($script, 'Normal', true, false);
  29. * $packed = $myPacker->pack();
  30. *
  31. * 또는 (기본값)
  32. *
  33. * $myPacker = new JavaScriptPacker($script);
  34. * $packed = $myPacker->pack();
  35. *
  36. *
  37. * 생성자의 매개변수:
  38. * $script: 팩할 JavaScript, 문자열.
  39. * $encoding: 인코딩 수준, int 또는 문자열:
  40. * 0,10,62,95 또는 'None', 'Numeric', 'Normal', 'High ASCII'.
  41. * 기본값: 62.
  42. * $fastDecode: 압축된 결과 부울에 빠른 디코더를 포함합니다.
  43. * 기본값 : true.
  44. * $specialChars: 개인 및 지역 변수가 플래그 지정된 경우
  45. * 스크립트에서 부울입니다.
  46. * 기본값: false.
  47. *
  48. * pack() 메소드는 압축된 JavaScript를 문자열로 반환합니다.
  49. *
  50. * 자세한 내용은 http://dean.edwards.name/packer/usage/를 참조하세요.
  51. *
  52. * 참고:
  53. * # PHP 5가 필요합니다. PHP 5.1.2, 5.1.3, 5.1.4, 5.2.3에서 테스트됨
  54. *
  55. * # 압축된 결과는 Dean Edwards
  56. * 버전과 다를 수 있지만 길이는 동일합니다. 그 이유는 배열을 정렬하는 PHP
  57. * 함수 usort가 반드시 두 개의 동일한 멤버의
  58. * 원래 순서를 유지하지 않기 때문입니다. Javascript 정렬 기능
  59. *은 실제로 이 순서를 유지합니다(그러나
  60. * ECMAScript 표준에서는 요구되지 않습니다). 따라서 두 결과에서 인코딩된 키워드 순서가
  61. * 다를 수 있습니다.
  62. *
  63. * # 파일에
  64. * UTF-8을 사용하는 경우 'High ASCII' 레벨 인코딩에 주의하세요...
  65. */
  66. class JavaScriptPacker {
  67. // 상수
  68. const IGNORE = '$1';
  69. // 매개변수 유효성 검사
  70. private $_script = '';
  71. 비공개 $_encoding = 62;
  72. 비공개 $_fastDecode = true;
  73. 비공개 $_specialChars = false;
  74. private $LITERAL_ENCODING = array(
  75. '없음' => 0,
  76. '숫자' => 10,
  77. '보통' => 62,
  78. '높음 ASCII' => 95
  79. );
  80. 공개 함수 __construct($_script, $_encoding = 62, $_fastDecode = true, $_specialChars = false)
  81. {
  82. $this->_script = $_script . "/N";
  83. if (array_key_exists($_encoding, $this->LITERAL_ENCODING))
  84. $_encoding = $this->LITERAL_ENCODING[$_encoding];
  85. $this->_encoding = min((int)$_encoding, 95);
  86. $this->_fastDecode = $_fastDecode;
  87. $this->_specialChars = $_specialChars;
  88. }
  89. 공용 함수 팩() {
  90. $this->_addParser('_basicCompression');
  91. if ($this->_specialChars)
  92. $this->_addParser('_encodeSpecialChars');
  93. if ($this->_encoding)
  94. $this->_addParser('_encodeKeywords');
  95. //가세요!
  96. return $this->_pack($this->_script);
  97. }
  98. // 모든 구문 분석 루틴 적용
  99. private function _pack($script) {
  100. for ($i = 0; isset($this->_parsers[$i]) ; $i ) {
  101. $script = call_user_func(array(&$this,$this->_parsers[$i]), $script);
  102. }
  103. return $script;
  104. }
  105. // 파싱 함수 목록을 유지하며 한꺼번에 실행됩니다.
  106. private $_parsers = array();
  107. 비공개 함수 _addParser($parser) {
  108. $this->_parsers[] = $parser;
  109. }
  110. // 인코딩 없음 - 공백과 주석만 제거
  111. private function _basicCompression($script) {
  112. $parser = new ParseMaster();
  113. // 안전하게 만듭니다
  114. $parser->escapeChar = '//';
  115. // 문자열 보호
  116. $parser->add('//'[^/'//n//r]*/'/', self::IGNORE);
  117. $parser->add('/"[^"//n//r]*"/', self::IGNORE);
  118. // 주석 제거
  119. $parser->add ('//////[^//n//r]*[//n//r]/', ' ')
  120. $parser->add('///// /*[^*]*//* ([^///][^*]*//* )*///', ' ')
  121. // 정규식 보호
  122. $parser ->add('///s (///[^/////n//r//*][^/////n//r]*///g?i?) /', '$2'); // 무시
  123. $parser->add('/[^//w//x24////'"*)//?:]///[^/ ////n//r//*][^/////n//r]*///g?i?/', self::IGNORE);
  124. // 제거: ;; doSomething();
  125. if ($this->_specialChars) $parser->add('/;;;[^//n//r] [//n//r]/');
  126. // 중복된 세미콜론 제거
  127. $parser->add('///(;;//)/', self::IGNORE); // (;;) 루프 보호
  128. $parser->add('/; //s*([};])/', '$2');
  129. // 위 내용을 적용합니다
  130. $script = $parser->exec($script);
  131. // 공백 제거
  132. $parser->add('/(//b|//x24)//s (//b|//x24)/', '$2 $3') ;
  133. $parser->add('/([ //-])//s ([ //-])/', '$2 $3');
  134. $parser->add('///s /', '');
  135. // 완료
  136. return $parser->exec($script);
  137. }
  138. 비공개 함수 _encodeSpecialChars($script) {
  139. $parser = new ParseMaster();
  140. // 교체: $name -> n, $$name -> na
  141. $parser->add('/((//x24 )([a-zA-Z$_] ))(//d*)/',
  142. array('fn' => ; '_replace_name')
  143. );
  144. // 교체: _name -> _0, 이중 밑줄(__name)은 무시됩니다.
  145. $regexp = '///b_[A-Za-z//d]//w*/';
  146. // 단어 목록 작성
  147. $keywords = $this->_analyze($script, $regexp, '_encodePrivate');
  148. // 빠른 참조
  149. $encoded = $keywords['encoded'];
  150. $parser->add($regexp,
  151. array(
  152. 'fn' => '_replace_encoded',
  153. 'data' => $encoded
  154. )
  155. );
  156. return $parser->exec($script);
  157. }
  158. private function _encodeKeywords($script) {
  159. // 이미 스크립트(예: 문자열)에 있는 상위 ASCII 값을 이스케이프합니다.
  160. if ($this->_encoding > 62)
  161. $script = $this->_escape95($script);
  162. // 파서 생성
  163. $parser = new ParseMaster();
  164. $encode = $this->_getEncoder($this->_encoding);
  165. // high-ascii의 경우 단일 문자 low-ascii를 인코딩하지 않습니다.
  166. $regexp = ($this->_encoding > 62) ? '///w//w /' : '///w /';
  167. // 단어 목록 작성
  168. $keywords = $this->_analyze($script, $regexp, $encode);
  169. $encoded = $keywords['인코딩'];
  170. // 인코딩
  171. $parser->add($regexp,
  172. array(
  173. 'fn' => '_replace_encoded',
  174. 'data' => $ 인코딩
  175. )
  176. );
  177. if (emptyempty($script)) return $script;
  178. else {
  179. //$res = $parser->exec($script);
  180. //$res = $this->_bootStrap($res, $keywords);
  181. //$res를 반환합니다.
  182. return $this->_bootStrap($parser->exec($script), $keywords);
  183. }
  184. }
  185. private function _analyze($script, $regexp, $encode) {
  186. // 분석
  187. // 스크립트의 모든 단어 검색
  188. $all = array();
  189. preg_match_all($regexp, $script, $all);
  190. $_sorted = 배열(); // 빈도순으로 정렬된 단어 목록
  191. $_encoded = array(); // 단어 사전->인코딩
  192. $_protected = array(); // "보호된" 단어의 인스턴스
  193. $all = $all[0]; // 전역 일치의 자바스크립트 구성을 시뮬레이션합니다.
  194. if (!emptyempty($all)) {
  195. $unsorted = array(); // 동일한 목록, 정렬되지 않음
  196. $protected = array(); // "보호된" 단어(단어->"단어" 사전)
  197. $value = array(); // charCode->인코딩 사전(예: 256->ff)
  198. $this->_count = array(); // 단어->개수
  199. $i = count($all); $j = 0; //$단어 = null;
  200. // 발생 횟수를 계산합니다. 나중에 정렬하는 데 사용됩니다.
  201. do {
  202. --$i;
  203. $워드 = '$' . $모두[$i];
  204. if (!isset($this->_count[$word])) {
  205. $this->_count[$word] = 0;
  206. $unsorted[$j] = $word;
  207. // 이 스크립트에 있는 모든 보호 단어의 사전을 만듭니다
  208. // 인코딩으로 오해할 수 있는 단어입니다.
  209. //if (is_string($encode) && method_exists($this, $ 인코딩))
  210. $values[$j] ​​= call_user_func(array(&$this, $encode), $j);
  211. $보호됨['$' . $values[$j]] = $j ;
  212. }
  213. // 단어 카운터를 증가시킵니다.
  214. $this->_count[$word] ;
  215. } while ($i > 0);
  216. // 단어 목록 정렬을 준비하려면 먼저
  217. // 코드로도 사용되는 단어를 보호해야 합니다. 단어 자체에 해당하는 코드
  218. //를 할당합니다.
  219. // 예: "do"가 인코딩 범위에 속하면
  220. // 키워드를 저장합니다.["do"] = "do";
  221. // 이는 디코딩 시 문제를 방지합니다.
  222. $i = count($unsorted);
  223. do {
  224. $word = $unsorted[--$i];
  225. if (isset($protected[$word]) /*!= null*/) {
  226. $_sorted[$protected[$word]] = substr($word, 1);
  227. $_protected[$protected[$word]] = 참;
  228. $this->_count[$word] = 0;
  229. }
  230. } while ($i);
  231. // 빈도순으로 단어 정렬
  232. // 참고: 정렬의 javascript 버전과 php 버전은 다를 수 있습니다.
  233. // php 매뉴얼에서는 usort :
  234. // " If two 멤버는 동일한 것으로 비교됩니다.
  235. // 정렬된 배열의 순서는 정의되지 않습니다."
  236. // 따라서 최종 압축 스크립트는 Dean의 자바스크립트 버전과 다릅니다.
  237. // 동일합니다.
  238. // ECMAscript 표준은 이 동작을 보장하지 않습니다.
  239. // 따라서 모든 브라우저(예:
  240. // 최소 2003년 이전의 Mozilla 버전)가 이를 존중하는 것은 아닙니다.
  241. usort($unsorted, array(&$this, '_sortWords'));
  242. $j = 0;
  243. // 목록에 "보호된" 단어가 있기 때문에
  244. // 그 주위에 정렬된 단어를 추가해야 합니다.
  245. do {
  246. if (!isset($_sorted[$i]))
  247. $_sorted[$i] = substr($unsorted[$j ], 1);
  248. $_encoded[$_sorted[$i]] = $values[$i];
  249. } while( $i < count($unsorted));
  250. }
  251. return array(
  252. 'sorted' => $_sorted,
  253. 'encoded' => $_encoded,
  254. 'protected' => $_protected);
  255. }
  256. private $_count = array();
  257. 비공개 함수 _sortWords($match1, $match2) {
  258. return $this->_count[$match2] - $this->_count[$match1];
  259. }
  260. // 로드 및 디코딩에 사용되는 부팅 함수를 빌드합니다.
  261. private function _bootStrap($packed, $keywords) {
  262. $ENCODE = $this->_safeRegExp('$encode//( $count//)');
  263. // $packed: 압축된 스크립트
  264. $packed = "'" . $this->_escape($packed) . "'";
  265. // $ascii: 인코딩 기반
  266. $ascii = min(count($keywords['sorted']), $this->_encoding);
  267. if ($ascii == 0) $ascii = 1;
  268. // $count: 스크립트에 포함된 단어 수
  269. $count = count($keywords['sorted']);
  270. // $keywords: 스크립트에 포함된 단어 목록
  271. foreach ($keywords['protected'] as $i=>$value) {
  272. $keywords['sorted'][$i ] = '';
  273. }
  274. // 문자열을 배열로 변환
  275. ksort($keywords['sorted']);
  276. $keywords = "'" . implode('|',$keywords['sorted']) . "'.split('|')";
  277. $encode = ($this->_encoding > 62) ? '_encode95' : $this->_getEncoder($ascii);
  278. $encode = $this->_getJSFunction($encode);
  279. $encode = preg_replace('/_encoding/','$ascii', $encode);
  280. $encode = preg_replace('/arguments//.callee/','$encode', $encode);
  281. $inline = '//$count' . ($ascii > 10 ? '.toString(//$ascii)' : '');
  282. // $decode: 디코딩 속도를 높이는 코드 조각
  283. if ($this->_fastDecode) {
  284. // 디코더 생성
  285. $decode = $this->_getJSFunction('_decodeBody ');
  286. if ($this->_encoding > 62)
  287. $decode = preg_replace('/////w/', '[//xa1-//xff]', $decode);
  288. // 낮은 ASCII 값에 대해 인라인 인코딩을 수행합니다.
  289. elseif ($ascii < 36)
  290. $decode = preg_replace($ENCODE, $inline, $decode);
  291. // 특수한 경우: $count==0일 때 키워드가 없습니다.
  292. // 언패킹 기능의 기본 모양을 유지하고 싶기 때문에 코드를 수정하겠습니다...
  293. if ($count == 0)
  294. $decode = preg_replace($this-> _safeRegExp('($count)//s*=//s*1'), '$1=0', $decode, 1);
  295. }
  296. // 부팅 함수
  297. $unpack = $this->_getJSFunction('_unpack');
  298. if ($this->_fastDecode) {
  299. // 디코더 삽입
  300. $this->buffer = $decode;
  301. $unpack = preg_replace_callback('///{/', array(&$this, '_insertFastDecode'), $unpack, 1);
  302. }
  303. $unpack = preg_replace('/"/', "'", $unpack);
  304. if ($this->_encoding > 62) { // high-ascii
  305. // 정규식 일치에 대한 단어 경계를 제거합니다.
  306. $unpack = preg_replace('//'////////b/'/s*// |// /s*/'// //////b/'/', '', $unpack)
  307. }
  308. if ($ascii > 36 || $this->_encoding > 62 || $this-> ;_fastDecode) {
  309. // 인코딩 함수 삽입
  310. $this->buffer = $encode;
  311. $unpack = preg_replace_callback('///{/', array(&$this, '_insertFastEncode '), $unpack, 1);
  312. } else {
  313. // 인코딩을 인라인으로 수행
  314. $unpack = preg_replace($ENCODE, $inline, $unpack)
  315. }
  316. / / 부팅 기능도 팩
  317. $unpackPacker = new JavaScriptPacker($unpack, 0, false, true)
  318. $unpack = $unpackPacker->pack()
  319. // 인수
  320. $params = array($packed, $ascii, $count, $keywords);
  321. if ($this->_fastDecode) {
  322. $params[] = 0;
  323. $params[] = '{}';
  324. }
  325. $params = implode(',', $params);
  326. // 전체
  327. return 'eval(' ​​. $unpack . '(' . $params . "))/n";
  328. }
  329. 비공개 $buffer;
  330. 비공개 함수 _insertFastDecode($match) {
  331. 반환 '{' . $this->버퍼 . ';';
  332. }
  333. 비공개 함수 _insertFastEncode($match) {
  334. return '{$encode=' . $this->버퍼 . ';';
  335. }
  336. // 음.. ..어떤 것이 필요합니까 ??
  337. 비공개 함수 _getEncoder($ascii) {
  338. return $ascii > 10? $ascii > 36? $ascii > 62?
  339. '_encode95' : '_encode62' : '_encode36' : '_encode10';
  340. }
  341. // 제로 인코딩
  342. // 문자: 0123456789
  343. 개인 함수 _encode10($charCode) {
  344. return $charCode;
  345. }
  346. // 기본 base36 지원
  347. // 문자: 0123456789abcdefghijklmnopqrstuvwxyz
  348. private function _encode36($charCode) {
  349. return base_convert($charCode, 10, 36);
  350. }
  351. // base36을 타고 대문자 알파벳 문자를 추가합니다.
  352. // 문자: 0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ
  353. private function _encode62($charCode) {
  354. $res = ' ';
  355. if ($charCode >= $this->_encoding) {
  356. $res = $this->_encode62((int)($charCode / $this->_encoding));
  357. }
  358. $charCode = $charCode % $this->_encoding;
  359. if ($charCode > 35)
  360. $res를 반환합니다. chr($charCode 29);
  361. else
  362. $res를 반환합니다. base_convert($charCode, 10, 36);
  363. }
  364. // 상위 ASCII 값 사용
  365. // 문자: ?¢£¤\|§¨?a??-?ˉ°±23′μ?·?1o?? ???àá????????èéê?ìí??D?òó???×?ùú?üYT?àáa????èéé?ìí??e?òó???¶?ùú?üyt
  366. 비공개 함수 _encode95($charCode) {
  367. $res = '';
  368. if ($charCode >= $this->_encoding)
  369. $res = $this->_encode95($charCode / $this->_encoding);
  370. $res를 반환합니다. chr(($charCode % $this->_encoding) 161);
  371. }
  372. 비공개 함수 _safeRegExp($string) {
  373. return '/'.preg_replace('//$/', '///$', $string).'/';
  374. }
  375. 프라이빗 함수 _encodePrivate($charCode) {
  376. return "_" . $charCode;
  377. }
  378. // 파서가 사용하는 문자 보호
  379. private function _escape($script) {
  380. return preg_replace('/([/////'])/', '///$1', $script);
  381. }
  382. // 이미 스크립트에 있는 상위 ASCII 문자를 보호합니다.
  383. private function _escape95($script) {
  384. return preg_replace_callback(
  385. '/[//xa1-// xff]/',
  386. array(&$this, '_escape95Bis'),
  387. $script
  388. );
  389. }
  390. private function _escape95Bis($match) {
  391. return '/x'.((string)dechex(ord($match)));
  392. }
  393. 비공개 함수 _getJSFunction($aName) {
  394. if (defed('self::JSFUNCTION'.$aName))
  395. return 상수('self::JSFUNCTION '.$a이름);
  396. else
  397. return '';
  398. }
  399. // 자바스크립트 함수를 사용합니다.
  400. // 참고: Dean 버전에서는 이러한 함수가
  401. // 'String(aFunctionName);'으로 변환됩니다.
  402. // 이 내부 변환은 원본 코드를 완성합니다. 예:
  403. // 'while (aBool) anAction();'
  404. 로 변환됩니다. // 'while (aBool) { anAction(); }'.
  405. // 아래 자바스크립트 함수가 수정되었습니다.
  406. // 언패킹 기능 - 이것은 부트 스트랩 기능입니다.
  407. // 이 패킹 루틴에서 추출된 데이터는
  408. 로 전달됩니다. // 타겟에서 디코딩될 때 이 함수
  409. // 참고 ! : ';' 없이 결정적인.
  410. const JSFUNCTION_unpack =
  411. 'function($packed, $ascii, $count, $keywords, $encode, $decode) {
  412. while ($count--) {
  413. if ($keywords[ $count]) {
  414. $packed = $packed.replace(new RegExp(/'////b/' $encode($count) /'////b/', /'g/') , $keywords[$count]);
  415. }
  416. }
  417. return $packed;
  418. }';
  419. /*
  420. 'function($packed, $ascii, $count, $keywords, $encode, $decode) {
  421. while ($count--)
  422. if ($keywords[$count ])
  423. $packed = $packed.replace(new RegExp(/'////b/' $encode($count) /'////b/', /'g/'), $keywords [$개수]);
  424. $packed를 반환합니다.
  425. }';
  426. */
  427. // 디코딩 속도를 높이기 위해 압축 해제기에 코드 조각을 삽입했습니다.
  428. const JSFUNCTION_decodeBody =
  429. //_decode = function() {
  430. // 브라우저가 지원합니까? String.replace 여기서
  431. // 대체 값은 함수인가요?
  432. ' if (!/'/'.replace(/^/, String)) {
  433. // 필요한 모든 값을 디코딩합니다
  434. while ($count--) {
  435. $decode[ $encode($count)] = $keywords[$count] || $인코드($count);
  436. }
  437. // 전역 대체 함수
  438. $keywords = [function ($encoded) {return $decode[$encoded]}];
  439. // 일반 일치
  440. $encode = function () {return /'////w /'};
  441. // 루프 카운터를 재설정합니다. 이제 전역 교체를 수행하고 있습니다.
  442. $count = 1;
  443. }
  444. ';
  445. //};
  446. /*
  447. ' if (!/'/'.replace(/^/, String)) {
  448. // 필요한 모든 값을 디코딩
  449. while ($count--) $decode [$encode($count)] = $keywords[$count] || $인코드($count);
  450. // 전역 대체 함수
  451. $keywords = [function ($encoded) {return $decode[$encoded]}];
  452. // 일반 일치
  453. $encode = function () {return/'////w /'};
  454. // 루프 카운터를 재설정합니다. 이제 전역 교체를 수행하고 있습니다.
  455. $count = 1;
  456. }';
  457. */
  458. // 제로 인코딩
  459. // 문자: 0123456789
  460. const JSFUNCTION_encode10 =
  461. 'function($charCode) {
  462. return $charCode;
  463. }';//;';
  464. // 고유한 base36 지원
  465. // 문자: 0123456789abcdefghijklmnopqrstuvwxyz
  466. const JSFUNCTION_encode36 =
  467. 'function($charCode) {
  468. return $charCode.toString(36);
  469. }';//;'; }';
  470. // 상위 ASCII 값 사용
  471. // 문자: ?¢£¤₩|§¨?a??-?ˉ°±23′μ?·?1o????àá ????????èéê?ìí??D?òó???×?ùú?üYT?àáa?????èéê?ìí??e?òó???¶?ùú?üyt
  472. const JSFUNCTION_encode95 =
  473. 'function($charCode) {
  474. return ($charCode < _encoding ? /'/' : 인수.callee($charCode / _encoding))
  475. String.fromCharCode($charCode % _encoding 161) ;
  476. }';
  477. }
  478. class ParseMaster {
  479. public $ignoreCase = false;
  480. 공개 $escapeChar = '';
  481. // 상수
  482. const EXPRESSION = 0;
  483. const 교체 = 1;
  484. const 길이 = 2;
  485. // 중첩 수준을 결정하는 데 사용됩니다.
  486. private $GROUPS = '///(/';//g
  487. private $SUB_REPLACE = '///$//d/';
  488. 비공개 $INDEXED = '/^//$//d $/';
  489. 비공개 $TRIM = '/([/'"])//1//.(.*)//.// 1//1$/';
  490. 비공개 $ESCAPE = '////./';//g
  491. 비공개 $QUOTE = '//'/'
  492. 비공개 $DELETED = '/ //x01[^//x01]*//x01/';//g
  493. public function add($expression, $replacement = '') {
  494. // 하위 개수를 계산합니다. 표현식
  495. // - 각 패턴 자체가 하위 표현식이므로 하나를 추가합니다.
  496. $length = 1 preg_match_all($this->GROUPS, $this->_internalEscape((string)$expression), $out );
  497. // 문자열만 처리 $replacement
  498. if (is_string($replacement)) {
  499. // 패턴이 하위 표현식을 처리합니까?
  500. if (preg_match($this) ->SUB_REPLACE, $replacement)) {
  501. // 간단한 조회인가요? (예: "$2")
  502. if (preg_match($this->INDEXED, $replacement)) {
  503. // 인덱스 저장(일치하는 문자열을 빠르게 검색하는 데 사용)
  504. $replacement = (int )(substr($replacement, 1)) - 1;
  505. } else { // 복잡한 조회(예: "Hello $2 $1")
  506. // 조회를 수행하는 함수 작성
  507. $quote = preg_match($this->QUOTE, $this-> ;_internalEscape($replacement))
  508. ? '"' : "'";
  509. $replacement = array(
  510. 'fn' => '_backReferences',
  511. 'data' => array(
  512. 'replacement' => $ 교체,
  513. '길이' => $length,
  514. 'quote' => $quote
  515. )
  516. )
  517. }
  518. }
  519. // 수정된 인수 전달
  520. if (!emptyempty($expression)) $this->_add($expression, $replacement, $length);
  521. else $this->_add('/^$/', $replacement, $length);
  522. }
  523. public function exec($string) {
  524. // 전역 교체 실행
  525. $this->_escaped = array();
  526. // Dean의 _patterns.toSTRing 시뮬레이션
  527. $regexp = '/';
  528. foreach ($this->_patterns as $reg) {
  529. $regexp .= '(' . substr($reg[self::EXPRESSION], 1, -1) . ')|';
  530. }
  531. $regexp = substr($regexp, 0, -1) . '/';
  532. $regexp .= ($this->ignoreCase) ? '나' : '';
  533. $string = $this->_escape($string, $this->escapeChar);
  534. $string = preg_replace_callback(
  535. $regexp,
  536. array(
  537. &$this,
  538. '_replacement'
  539. ),
  540. $string
  541. );
  542. $string = $this->_unescape($string, $this->escapeChar);
  543. return preg_replace($this->DELETED, '', $string);
  544. }
  545. public function Reset() {
  546. // 이 객체를 재사용할 수 있도록 패턴 컬렉션을 지웁니다.
  547. $this->_patterns = array();
  548. }
  549. // 비공개
  550. 비공개 $_escaped = array(); // 이스케이프된 문자
  551. private $_patterns = array(); // 인덱스에 저장된 패턴
  552. // 새 패턴을 생성하고 패턴 컬렉션에 추가
  553. private function _add() {
  554. $arguments = func_get_args();
  555. $this->_patterns[] = $arguments;
  556. }
  557. // 전역 대체 함수입니다(상당히 복잡합니다)
  558. private function _replacement($arguments) {
  559. if (emptyempty($arguments)) return '';
  560. $i = 1; $j = 0;
  561. // 패턴을 반복합니다.
  562. while (isset($this->_patterns[$j])) {
  563. $pattern = $this->_patterns[$j ];
  564. //결과가 있나요?
  565. if (isset($arguments[$i]) && ($arguments[$i] != '')) {
  566. $replacement = $pattern[self::REPLACEMENT];
  567. if (is_array($replacement) && isset($replacement['fn'])) {
  568. if (isset($replacement['data'])) $this-> 버퍼 = $replacement['데이터'];
  569. return call_user_func(array(&$this, $replacement['fn']), $arguments, $i);
  570. } elseif (is_int($replacement)) {
  571. return $arguments[$replacement $i];
  572. }
  573. $delete = ($this->escapeChar == '' ||
  574. strpos($arguments[$i], $this->escapeChar) === false)
  575. ? '' : "/x01" . $인수[$i] . "/x01";
  576. $delete를 반환합니다. $교체;
  577. // 하위 표현식에 대한 참조를 건너뜁니다.
  578. } else {
  579. $i = $pattern[self::LENGTH];
  580. }
  581. }
  582. }
  583. 비공개 함수 _backReferences($match, $offset) {
  584. $replacement = $this->buffer['replacement'];
  585. $quote = $this->버퍼['quote'];
  586. $i = $this->버퍼['길이'];
  587. while ($i) {
  588. $replacement = str_replace('$'.$i--, $match[$offset $i], $replacement);
  589. }
  590. $replacement를 반환합니다.
  591. }
  592. 비공개 함수 _replace_name($match, $offset){
  593. $length = strlen($match[$offset 2]);
  594. $start = $length - max($length - strlen($match[$offset 3]), 0);
  595. substr($match[$offset 1], $start, $length) 를 반환합니다. $match[$offset 4];
  596. }
  597. 비공개 함수 _replace_encoded($match, $offset) {
  598. return $this->buffer[$match[$offset]];
  599. }
  600. // php : preg_replace_callback에 추가 데이터를 전달할 수 없습니다.
  601. // 그리고 create_function에서 &$this를 사용할 수 없으므로 더 낮은 수준으로 이동하겠습니다.
  602. private $buffer;
  603. // 이스케이프 문자 인코딩
  604. private function _escape($string, $escapeChar) {
  605. if ($escapeChar) {
  606. $this->buffer = $escapeChar;
  607. return preg_replace_callback(
  608. '///' . $escapeChar . '(.)' .'/',
  609. array(&$this, '_escapeBis'),
  610. $string
  611. );
  612. } else {
  613. return $string;
  614. }
  615. }
  616. 비공개 함수 _escapeBis($match) {
  617. $this->_escaped[] = $match[1];
  618. return $this->buffer;
  619. }
  620. // 이스케이프 문자 디코딩
  621. private function _unescape($string, $escapeChar) {
  622. if ($escapeChar) {
  623. $regexp = '/'.'/ /'.$escapeChar.'/';
  624. $this->buffer = array('escapeChar'=> $escapeChar, 'i' => 0);
  625. return preg_replace_callback
  626. (
  627. $regexp,
  628. array(&$this, '_unescapeBis'),
  629. $string
  630. );
  631. } else {
  632. return $string;
  633. }
  634. }
  635. 비공개 함수 _unescapeBis() {
  636. if (isset($this->_escaped[$this->buffer['i']])
  637. && $this ->_escaped[$this->buffer['i']] != '')
  638. {
  639. $temp = $this->_escaped[$this->buffer['i'] ];
  640. } else {
  641. $temp = '';
  642. }
  643. $this->buffer['i'] ;
  644. $this->buffer['escapeChar'] 를 반환합니다. $ 임시;
  645. }
  646. private function _internalEscape($string) {
  647. return preg_replace($this->ESCAPE, '', $string);
  648. }
  649. }
  650. ?>
제제대码

2、이동 PHP 문서는 pack_js_file.php를 사용합니다.

  1. require 'tom-class.JavaScriptPacker.php';
  2. $t1 = 마이크로타임(true);
  3. $source_dir = realpath(dirname(__FILE__)."/..")."/common/script_unpacked";
  4. $out_dir = realpath(dirname(__FILE__)."/..")."/common/script";
  5. $d = dir( $source_dir );
  6. //echo "핸들: " . $d->핸들 . "/N";
  7. //에코 "경로: " . $d->경로 . "/N";
  8. while (false !== ($entry = $d->read())) {
  9. if($entry=='.') continue;
  10. if($entry=='..') 계속;
  11. if($entry=='.svn') 계속;
  12. echo $entry."/n";
  13. $script = file_get_contents($source_dir.'/'.$entry);
  14. $packer = new JavaScriptPacker($script, 'Normal', true, false);
  15. $packed = $packer->pack();
  16. file_put_contents($out_dir. '/'. $entry, $packed);
  17. }
  18. $d->close();
  19. $t2 = 마이크로타임(true);
  20. $time = sprintf('%.4f', ($t2 - $t1) );
  21. echo 'script in ', $time, ' s.', "/n";
  22. 죽다;
  23. ?>
复代代码

3、创建一个自动执行的bat文件。 文件中输入如下下内容 : /usr/local/php/bin/php pack_js_file.php

总结: 只要填好相对路径或者绝对路径,一键加密JS完成,那是相当的方便!!



본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.

핫 AI 도구

Undresser.AI Undress

Undresser.AI Undress

사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover

AI Clothes Remover

사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool

Undress AI Tool

무료로 이미지를 벗다

Clothoff.io

Clothoff.io

AI 옷 제거제

AI Hentai Generator

AI Hentai Generator

AI Hentai를 무료로 생성하십시오.

뜨거운 도구

메모장++7.3.1

메모장++7.3.1

사용하기 쉬운 무료 코드 편집기

SublimeText3 중국어 버전

SublimeText3 중국어 버전

중국어 버전, 사용하기 매우 쉽습니다.

스튜디오 13.0.1 보내기

스튜디오 13.0.1 보내기

강력한 PHP 통합 개발 환경

드림위버 CS6

드림위버 CS6

시각적 웹 개발 도구

SublimeText3 Mac 버전

SublimeText3 Mac 버전

신 수준의 코드 편집 소프트웨어(SublimeText3)

11 최고의 PHP URL 쇼트너 스크립트 (무료 및 프리미엄) 11 최고의 PHP URL 쇼트너 스크립트 (무료 및 프리미엄) Mar 03, 2025 am 10:49 AM

종종 키워드와 추적 매개 변수로 혼란스러워하는 긴 URL은 방문자를 방해 할 수 있습니다. URL 단축 스크립트는 솔루션을 제공하여 소셜 미디어 및 기타 플랫폼에 이상적인 간결한 링크를 만듭니다. 이 스크립트는 개별 웹 사이트 a에 유용합니다

Instagram API 소개 Instagram API 소개 Mar 02, 2025 am 09:32 AM

Instagram은 2012 년 Facebook에서 유명한 인수에 이어 타사 사용을 위해 두 개의 API 세트를 채택했습니다. Instagram Graph API 및 Instagram Basic Display API입니다. 개발자는

Laravel의 플래시 세션 데이터로 작업합니다 Laravel의 플래시 세션 데이터로 작업합니다 Mar 12, 2025 pm 05:08 PM

Laravel은 직관적 인 플래시 방법을 사용하여 임시 세션 데이터 처리를 단순화합니다. 응용 프로그램에 간단한 메시지, 경고 또는 알림을 표시하는 데 적합합니다. 데이터는 기본적으로 후속 요청에만 지속됩니다. $ 요청-

Laravel Back End : Part 2, React가있는 React 앱 구축 Laravel Back End : Part 2, React가있는 React 앱 구축 Mar 04, 2025 am 09:33 AM

이것은 Laravel 백엔드가있는 React Application을 구축하는 데있어 시리즈의 두 번째이자 마지막 부분입니다. 이 시리즈의 첫 번째 부분에서는 기본 제품 목록 응용 프로그램을 위해 Laravel을 사용하여 편안한 API를 만들었습니다. 이 튜토리얼에서는 Dev가 될 것입니다

Laravel 테스트에서 단순화 된 HTTP 응답 조롱 Laravel 테스트에서 단순화 된 HTTP 응답 조롱 Mar 12, 2025 pm 05:09 PM

Laravel은 간결한 HTTP 응답 시뮬레이션 구문을 제공하여 HTTP 상호 작용 테스트를 단순화합니다. 이 접근법은 테스트 시뮬레이션을보다 직관적으로 만들면서 코드 중복성을 크게 줄입니다. 기본 구현은 다양한 응답 유형 단축키를 제공합니다. Illuminate \ support \ Facades \ http를 사용하십시오. http :: 가짜 ([ 'google.com'=> ​​'Hello World', 'github.com'=> ​​[ 'foo'=> 'bar'], 'forge.laravel.com'=>

PHP의 컬 : REST API에서 PHP Curl Extension 사용 방법 PHP의 컬 : REST API에서 PHP Curl Extension 사용 방법 Mar 14, 2025 am 11:42 AM

PHP 클라이언트 URL (CURL) 확장자는 개발자를위한 강력한 도구이며 원격 서버 및 REST API와의 원활한 상호 작용을 가능하게합니다. PHP CURL은 존경받는 다중 프로모토콜 파일 전송 라이브러리 인 Libcurl을 활용하여 효율적인 execu를 용이하게합니다.

Codecanyon에서 12 개의 최고의 PHP 채팅 스크립트 Codecanyon에서 12 개의 최고의 PHP 채팅 스크립트 Mar 13, 2025 pm 12:08 PM

고객의 가장 긴급한 문제에 실시간 인스턴트 솔루션을 제공하고 싶습니까? 라이브 채팅을 통해 고객과 실시간 대화를 나누고 문제를 즉시 해결할 수 있습니다. 그것은 당신이 당신의 관습에 더 빠른 서비스를 제공 할 수 있도록합니다.

2025 PHP 상황 조사 발표 2025 PHP 상황 조사 발표 Mar 03, 2025 pm 04:20 PM

2025 PHP Landscape Survey는 현재 PHP 개발 동향을 조사합니다. 개발자와 비즈니스에 대한 통찰력을 제공하는 프레임 워크 사용, 배포 방법 및 과제를 탐색합니다. 이 조사는 현대 PHP Versio의 성장을 예상합니다

See all articles