PageRenderTime 55ms CodeModel.GetById 23ms RepoModel.GetById 1ms app.codeStats 0ms

/ext/pcre/php_pcre.c

http://github.com/infusion/PHP
C | 1932 lines | 1395 code | 250 blank | 287 comment | 370 complexity | aaa2d91781bfab0110c1497869565e07 MD5 | raw file
Possible License(s): MPL-2.0-no-copyleft-exception, LGPL-2.1, BSD-3-Clause

Large files files are truncated, but you can click here to view the full file

  1. /*
  2. +----------------------------------------------------------------------+
  3. | PHP Version 5 |
  4. +----------------------------------------------------------------------+
  5. | Copyright (c) 1997-2011 The PHP Group |
  6. +----------------------------------------------------------------------+
  7. | This source file is subject to version 3.01 of the PHP license, |
  8. | that is bundled with this package in the file LICENSE, and is |
  9. | available through the world-wide-web at the following url: |
  10. | http://www.php.net/license/3_01.txt |
  11. | If you did not receive a copy of the PHP license and are unable to |
  12. | obtain it through the world-wide-web, please send a note to |
  13. | license@php.net so we can mail you a copy immediately. |
  14. +----------------------------------------------------------------------+
  15. | Author: Andrei Zmievski <andrei@php.net> |
  16. +----------------------------------------------------------------------+
  17. */
  18. /* $Id: php_pcre.c 306939 2011-01-01 02:19:59Z felipe $ */
  19. #include "php.h"
  20. #include "php_ini.h"
  21. #include "php_globals.h"
  22. #include "php_pcre.h"
  23. #include "ext/standard/info.h"
  24. #include "ext/standard/php_smart_str.h"
  25. #if HAVE_PCRE || HAVE_BUNDLED_PCRE
  26. #include "ext/standard/php_string.h"
  27. #define PREG_PATTERN_ORDER 1
  28. #define PREG_SET_ORDER 2
  29. #define PREG_OFFSET_CAPTURE (1<<8)
  30. #define PREG_SPLIT_NO_EMPTY (1<<0)
  31. #define PREG_SPLIT_DELIM_CAPTURE (1<<1)
  32. #define PREG_SPLIT_OFFSET_CAPTURE (1<<2)
  33. #define PREG_REPLACE_EVAL (1<<0)
  34. #define PREG_GREP_INVERT (1<<0)
  35. #define PCRE_CACHE_SIZE 4096
  36. enum {
  37. PHP_PCRE_NO_ERROR = 0,
  38. PHP_PCRE_INTERNAL_ERROR,
  39. PHP_PCRE_BACKTRACK_LIMIT_ERROR,
  40. PHP_PCRE_RECURSION_LIMIT_ERROR,
  41. PHP_PCRE_BAD_UTF8_ERROR,
  42. PHP_PCRE_BAD_UTF8_OFFSET_ERROR
  43. };
  44. ZEND_DECLARE_MODULE_GLOBALS(pcre)
  45. static void pcre_handle_exec_error(int pcre_code TSRMLS_DC) /* {{{ */
  46. {
  47. int preg_code = 0;
  48. switch (pcre_code) {
  49. case PCRE_ERROR_MATCHLIMIT:
  50. preg_code = PHP_PCRE_BACKTRACK_LIMIT_ERROR;
  51. break;
  52. case PCRE_ERROR_RECURSIONLIMIT:
  53. preg_code = PHP_PCRE_RECURSION_LIMIT_ERROR;
  54. break;
  55. case PCRE_ERROR_BADUTF8:
  56. preg_code = PHP_PCRE_BAD_UTF8_ERROR;
  57. break;
  58. case PCRE_ERROR_BADUTF8_OFFSET:
  59. preg_code = PHP_PCRE_BAD_UTF8_OFFSET_ERROR;
  60. break;
  61. default:
  62. preg_code = PHP_PCRE_INTERNAL_ERROR;
  63. break;
  64. }
  65. PCRE_G(error_code) = preg_code;
  66. }
  67. /* }}} */
  68. static void php_free_pcre_cache(void *data) /* {{{ */
  69. {
  70. pcre_cache_entry *pce = (pcre_cache_entry *) data;
  71. if (!pce) return;
  72. pefree(pce->re, 1);
  73. if (pce->extra) pefree(pce->extra, 1);
  74. #if HAVE_SETLOCALE
  75. if ((void*)pce->tables) pefree((void*)pce->tables, 1);
  76. pefree(pce->locale, 1);
  77. #endif
  78. }
  79. /* }}} */
  80. static PHP_GINIT_FUNCTION(pcre) /* {{{ */
  81. {
  82. zend_hash_init(&pcre_globals->pcre_cache, 0, NULL, php_free_pcre_cache, 1);
  83. pcre_globals->backtrack_limit = 0;
  84. pcre_globals->recursion_limit = 0;
  85. pcre_globals->error_code = PHP_PCRE_NO_ERROR;
  86. }
  87. /* }}} */
  88. static PHP_GSHUTDOWN_FUNCTION(pcre) /* {{{ */
  89. {
  90. zend_hash_destroy(&pcre_globals->pcre_cache);
  91. }
  92. /* }}} */
  93. PHP_INI_BEGIN()
  94. STD_PHP_INI_ENTRY("pcre.backtrack_limit", "100000", PHP_INI_ALL, OnUpdateLong, backtrack_limit, zend_pcre_globals, pcre_globals)
  95. STD_PHP_INI_ENTRY("pcre.recursion_limit", "100000", PHP_INI_ALL, OnUpdateLong, recursion_limit, zend_pcre_globals, pcre_globals)
  96. PHP_INI_END()
  97. /* {{{ PHP_MINFO_FUNCTION(pcre) */
  98. static PHP_MINFO_FUNCTION(pcre)
  99. {
  100. php_info_print_table_start();
  101. php_info_print_table_row(2, "PCRE (Perl Compatible Regular Expressions) Support", "enabled" );
  102. php_info_print_table_row(2, "PCRE Library Version", pcre_version() );
  103. php_info_print_table_end();
  104. DISPLAY_INI_ENTRIES();
  105. }
  106. /* }}} */
  107. /* {{{ PHP_MINIT_FUNCTION(pcre) */
  108. static PHP_MINIT_FUNCTION(pcre)
  109. {
  110. REGISTER_INI_ENTRIES();
  111. REGISTER_LONG_CONSTANT("PREG_PATTERN_ORDER", PREG_PATTERN_ORDER, CONST_CS | CONST_PERSISTENT);
  112. REGISTER_LONG_CONSTANT("PREG_SET_ORDER", PREG_SET_ORDER, CONST_CS | CONST_PERSISTENT);
  113. REGISTER_LONG_CONSTANT("PREG_OFFSET_CAPTURE", PREG_OFFSET_CAPTURE, CONST_CS | CONST_PERSISTENT);
  114. REGISTER_LONG_CONSTANT("PREG_SPLIT_NO_EMPTY", PREG_SPLIT_NO_EMPTY, CONST_CS | CONST_PERSISTENT);
  115. REGISTER_LONG_CONSTANT("PREG_SPLIT_DELIM_CAPTURE", PREG_SPLIT_DELIM_CAPTURE, CONST_CS | CONST_PERSISTENT);
  116. REGISTER_LONG_CONSTANT("PREG_SPLIT_OFFSET_CAPTURE", PREG_SPLIT_OFFSET_CAPTURE, CONST_CS | CONST_PERSISTENT);
  117. REGISTER_LONG_CONSTANT("PREG_GREP_INVERT", PREG_GREP_INVERT, CONST_CS | CONST_PERSISTENT);
  118. REGISTER_LONG_CONSTANT("PREG_NO_ERROR", PHP_PCRE_NO_ERROR, CONST_CS | CONST_PERSISTENT);
  119. REGISTER_LONG_CONSTANT("PREG_INTERNAL_ERROR", PHP_PCRE_INTERNAL_ERROR, CONST_CS | CONST_PERSISTENT);
  120. REGISTER_LONG_CONSTANT("PREG_BACKTRACK_LIMIT_ERROR", PHP_PCRE_BACKTRACK_LIMIT_ERROR, CONST_CS | CONST_PERSISTENT);
  121. REGISTER_LONG_CONSTANT("PREG_RECURSION_LIMIT_ERROR", PHP_PCRE_RECURSION_LIMIT_ERROR, CONST_CS | CONST_PERSISTENT);
  122. REGISTER_LONG_CONSTANT("PREG_BAD_UTF8_ERROR", PHP_PCRE_BAD_UTF8_ERROR, CONST_CS | CONST_PERSISTENT);
  123. REGISTER_LONG_CONSTANT("PREG_BAD_UTF8_OFFSET_ERROR", PHP_PCRE_BAD_UTF8_OFFSET_ERROR, CONST_CS | CONST_PERSISTENT);
  124. REGISTER_STRING_CONSTANT("PCRE_VERSION", (char *)pcre_version(), CONST_CS | CONST_PERSISTENT);
  125. return SUCCESS;
  126. }
  127. /* }}} */
  128. /* {{{ PHP_MSHUTDOWN_FUNCTION(pcre) */
  129. static PHP_MSHUTDOWN_FUNCTION(pcre)
  130. {
  131. UNREGISTER_INI_ENTRIES();
  132. return SUCCESS;
  133. }
  134. /* }}} */
  135. /* {{{ static pcre_clean_cache */
  136. static int pcre_clean_cache(void *data, void *arg TSRMLS_DC)
  137. {
  138. int *num_clean = (int *)arg;
  139. if (*num_clean > 0) {
  140. (*num_clean)--;
  141. return 1;
  142. } else {
  143. return 0;
  144. }
  145. }
  146. /* }}} */
  147. /* {{{ static make_subpats_table */
  148. static char **make_subpats_table(int num_subpats, pcre_cache_entry *pce TSRMLS_DC)
  149. {
  150. pcre_extra *extra = pce->extra;
  151. int name_cnt = 0, name_size, ni = 0;
  152. int rc;
  153. char *name_table;
  154. unsigned short name_idx;
  155. char **subpat_names = (char **)ecalloc(num_subpats, sizeof(char *));
  156. rc = pcre_fullinfo(pce->re, extra, PCRE_INFO_NAMECOUNT, &name_cnt);
  157. if (rc < 0) {
  158. php_error_docref(NULL TSRMLS_CC, E_WARNING, "Internal pcre_fullinfo() error %d", rc);
  159. efree(subpat_names);
  160. return NULL;
  161. }
  162. if (name_cnt > 0) {
  163. int rc1, rc2;
  164. rc1 = pcre_fullinfo(pce->re, extra, PCRE_INFO_NAMETABLE, &name_table);
  165. rc2 = pcre_fullinfo(pce->re, extra, PCRE_INFO_NAMEENTRYSIZE, &name_size);
  166. rc = rc2 ? rc2 : rc1;
  167. if (rc < 0) {
  168. php_error_docref(NULL TSRMLS_CC, E_WARNING, "Internal pcre_fullinfo() error %d", rc);
  169. efree(subpat_names);
  170. return NULL;
  171. }
  172. while (ni++ < name_cnt) {
  173. name_idx = 0xff * (unsigned char)name_table[0] + (unsigned char)name_table[1];
  174. subpat_names[name_idx] = name_table + 2;
  175. if (is_numeric_string(subpat_names[name_idx], strlen(subpat_names[name_idx]), NULL, NULL, 0) > 0) {
  176. php_error_docref(NULL TSRMLS_CC, E_WARNING, "Numeric named subpatterns are not allowed");
  177. efree(subpat_names);
  178. return NULL;
  179. }
  180. name_table += name_size;
  181. }
  182. }
  183. return subpat_names;
  184. }
  185. /* }}} */
  186. /* {{{ pcre_get_compiled_regex_cache
  187. */
  188. PHPAPI pcre_cache_entry* pcre_get_compiled_regex_cache(char *regex, int regex_len TSRMLS_DC)
  189. {
  190. pcre *re = NULL;
  191. pcre_extra *extra;
  192. int coptions = 0;
  193. int soptions = 0;
  194. const char *error;
  195. int erroffset;
  196. char delimiter;
  197. char start_delimiter;
  198. char end_delimiter;
  199. char *p, *pp;
  200. char *pattern;
  201. int do_study = 0;
  202. int poptions = 0;
  203. unsigned const char *tables = NULL;
  204. #if HAVE_SETLOCALE
  205. char *locale = setlocale(LC_CTYPE, NULL);
  206. #endif
  207. pcre_cache_entry *pce;
  208. pcre_cache_entry new_entry;
  209. /* Try to lookup the cached regex entry, and if successful, just pass
  210. back the compiled pattern, otherwise go on and compile it. */
  211. if (zend_hash_find(&PCRE_G(pcre_cache), regex, regex_len+1, (void **)&pce) == SUCCESS) {
  212. /*
  213. * We use a quick pcre_info() check to see whether cache is corrupted, and if it
  214. * is, we flush it and compile the pattern from scratch.
  215. */
  216. if (pcre_info(pce->re, NULL, NULL) == PCRE_ERROR_BADMAGIC) {
  217. zend_hash_clean(&PCRE_G(pcre_cache));
  218. } else {
  219. #if HAVE_SETLOCALE
  220. if (!strcmp(pce->locale, locale)) {
  221. #endif
  222. return pce;
  223. #if HAVE_SETLOCALE
  224. }
  225. #endif
  226. }
  227. }
  228. p = regex;
  229. /* Parse through the leading whitespace, and display a warning if we
  230. get to the end without encountering a delimiter. */
  231. while (isspace((int)*(unsigned char *)p)) p++;
  232. if (*p == 0) {
  233. php_error_docref(NULL TSRMLS_CC, E_WARNING, "Empty regular expression");
  234. return NULL;
  235. }
  236. /* Get the delimiter and display a warning if it is alphanumeric
  237. or a backslash. */
  238. delimiter = *p++;
  239. if (isalnum((int)*(unsigned char *)&delimiter) || delimiter == '\\') {
  240. php_error_docref(NULL TSRMLS_CC,E_WARNING, "Delimiter must not be alphanumeric or backslash");
  241. return NULL;
  242. }
  243. start_delimiter = delimiter;
  244. if ((pp = strchr("([{< )]}> )]}>", delimiter)))
  245. delimiter = pp[5];
  246. end_delimiter = delimiter;
  247. if (start_delimiter == end_delimiter) {
  248. /* We need to iterate through the pattern, searching for the ending delimiter,
  249. but skipping the backslashed delimiters. If the ending delimiter is not
  250. found, display a warning. */
  251. pp = p;
  252. while (*pp != 0) {
  253. if (*pp == '\\' && pp[1] != 0) pp++;
  254. else if (*pp == delimiter)
  255. break;
  256. pp++;
  257. }
  258. if (*pp == 0) {
  259. php_error_docref(NULL TSRMLS_CC,E_WARNING, "No ending delimiter '%c' found", delimiter);
  260. return NULL;
  261. }
  262. } else {
  263. /* We iterate through the pattern, searching for the matching ending
  264. * delimiter. For each matching starting delimiter, we increment nesting
  265. * level, and decrement it for each matching ending delimiter. If we
  266. * reach the end of the pattern without matching, display a warning.
  267. */
  268. int brackets = 1; /* brackets nesting level */
  269. pp = p;
  270. while (*pp != 0) {
  271. if (*pp == '\\' && pp[1] != 0) pp++;
  272. else if (*pp == end_delimiter && --brackets <= 0)
  273. break;
  274. else if (*pp == start_delimiter)
  275. brackets++;
  276. pp++;
  277. }
  278. if (*pp == 0) {
  279. php_error_docref(NULL TSRMLS_CC,E_WARNING, "No ending matching delimiter '%c' found", end_delimiter);
  280. return NULL;
  281. }
  282. }
  283. /* Make a copy of the actual pattern. */
  284. pattern = estrndup(p, pp-p);
  285. /* Move on to the options */
  286. pp++;
  287. /* Parse through the options, setting appropriate flags. Display
  288. a warning if we encounter an unknown modifier. */
  289. while (*pp != 0) {
  290. switch (*pp++) {
  291. /* Perl compatible options */
  292. case 'i': coptions |= PCRE_CASELESS; break;
  293. case 'm': coptions |= PCRE_MULTILINE; break;
  294. case 's': coptions |= PCRE_DOTALL; break;
  295. case 'x': coptions |= PCRE_EXTENDED; break;
  296. /* PCRE specific options */
  297. case 'A': coptions |= PCRE_ANCHORED; break;
  298. case 'D': coptions |= PCRE_DOLLAR_ENDONLY;break;
  299. case 'S': do_study = 1; break;
  300. case 'U': coptions |= PCRE_UNGREEDY; break;
  301. case 'X': coptions |= PCRE_EXTRA; break;
  302. case 'u': coptions |= PCRE_UTF8;
  303. /* In PCRE, by default, \d, \D, \s, \S, \w, and \W recognize only ASCII
  304. characters, even in UTF-8 mode. However, this can be changed by setting
  305. the PCRE_UCP option. */
  306. #ifdef PCRE_UCP
  307. coptions |= PCRE_UCP;
  308. #endif
  309. break;
  310. /* Custom preg options */
  311. case 'e': poptions |= PREG_REPLACE_EVAL; break;
  312. case ' ':
  313. case '\n':
  314. break;
  315. default:
  316. php_error_docref(NULL TSRMLS_CC,E_WARNING, "Unknown modifier '%c'", pp[-1]);
  317. efree(pattern);
  318. return NULL;
  319. }
  320. }
  321. #if HAVE_SETLOCALE
  322. if (strcmp(locale, "C"))
  323. tables = pcre_maketables();
  324. #endif
  325. /* Compile pattern and display a warning if compilation failed. */
  326. re = pcre_compile(pattern,
  327. coptions,
  328. &error,
  329. &erroffset,
  330. tables);
  331. if (re == NULL) {
  332. php_error_docref(NULL TSRMLS_CC,E_WARNING, "Compilation failed: %s at offset %d", error, erroffset);
  333. efree(pattern);
  334. if (tables) {
  335. pefree((void*)tables, 1);
  336. }
  337. return NULL;
  338. }
  339. /* If study option was specified, study the pattern and
  340. store the result in extra for passing to pcre_exec. */
  341. if (do_study) {
  342. extra = pcre_study(re, soptions, &error);
  343. if (extra) {
  344. extra->flags |= PCRE_EXTRA_MATCH_LIMIT | PCRE_EXTRA_MATCH_LIMIT_RECURSION;
  345. }
  346. if (error != NULL) {
  347. php_error_docref(NULL TSRMLS_CC, E_WARNING, "Error while studying pattern");
  348. }
  349. } else {
  350. extra = NULL;
  351. }
  352. efree(pattern);
  353. /*
  354. * If we reached cache limit, clean out the items from the head of the list;
  355. * these are supposedly the oldest ones (but not necessarily the least used
  356. * ones).
  357. */
  358. if (zend_hash_num_elements(&PCRE_G(pcre_cache)) == PCRE_CACHE_SIZE) {
  359. int num_clean = PCRE_CACHE_SIZE / 8;
  360. zend_hash_apply_with_argument(&PCRE_G(pcre_cache), pcre_clean_cache, &num_clean TSRMLS_CC);
  361. }
  362. /* Store the compiled pattern and extra info in the cache. */
  363. new_entry.re = re;
  364. new_entry.extra = extra;
  365. new_entry.preg_options = poptions;
  366. new_entry.compile_options = coptions;
  367. #if HAVE_SETLOCALE
  368. new_entry.locale = pestrdup(locale, 1);
  369. new_entry.tables = tables;
  370. #endif
  371. zend_hash_update(&PCRE_G(pcre_cache), regex, regex_len+1, (void *)&new_entry,
  372. sizeof(pcre_cache_entry), (void**)&pce);
  373. return pce;
  374. }
  375. /* }}} */
  376. /* {{{ pcre_get_compiled_regex
  377. */
  378. PHPAPI pcre* pcre_get_compiled_regex(char *regex, pcre_extra **extra, int *preg_options TSRMLS_DC)
  379. {
  380. pcre_cache_entry * pce = pcre_get_compiled_regex_cache(regex, strlen(regex) TSRMLS_CC);
  381. if (extra) {
  382. *extra = pce ? pce->extra : NULL;
  383. }
  384. if (preg_options) {
  385. *preg_options = pce ? pce->preg_options : 0;
  386. }
  387. return pce ? pce->re : NULL;
  388. }
  389. /* }}} */
  390. /* {{{ pcre_get_compiled_regex_ex
  391. */
  392. PHPAPI pcre* pcre_get_compiled_regex_ex(char *regex, pcre_extra **extra, int *preg_options, int *compile_options TSRMLS_DC)
  393. {
  394. pcre_cache_entry * pce = pcre_get_compiled_regex_cache(regex, strlen(regex) TSRMLS_CC);
  395. if (extra) {
  396. *extra = pce ? pce->extra : NULL;
  397. }
  398. if (preg_options) {
  399. *preg_options = pce ? pce->preg_options : 0;
  400. }
  401. if (compile_options) {
  402. *compile_options = pce ? pce->compile_options : 0;
  403. }
  404. return pce ? pce->re : NULL;
  405. }
  406. /* }}} */
  407. /* {{{ add_offset_pair */
  408. static inline void add_offset_pair(zval *result, char *str, int len, int offset, char *name)
  409. {
  410. zval *match_pair;
  411. ALLOC_ZVAL(match_pair);
  412. array_init(match_pair);
  413. INIT_PZVAL(match_pair);
  414. /* Add (match, offset) to the return value */
  415. add_next_index_stringl(match_pair, str, len, 1);
  416. add_next_index_long(match_pair, offset);
  417. if (name) {
  418. zval_add_ref(&match_pair);
  419. zend_hash_update(Z_ARRVAL_P(result), name, strlen(name)+1, &match_pair, sizeof(zval *), NULL);
  420. }
  421. zend_hash_next_index_insert(Z_ARRVAL_P(result), &match_pair, sizeof(zval *), NULL);
  422. }
  423. /* }}} */
  424. static void php_do_pcre_match(INTERNAL_FUNCTION_PARAMETERS, int global) /* {{{ */
  425. {
  426. /* parameters */
  427. char *regex; /* Regular expression */
  428. char *subject; /* String to match against */
  429. int regex_len;
  430. int subject_len;
  431. pcre_cache_entry *pce; /* Compiled regular expression */
  432. zval *subpats = NULL; /* Array for subpatterns */
  433. long flags = 0; /* Match control flags */
  434. long start_offset = 0; /* Where the new search starts */
  435. if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, ((global) ? "ssz|ll" : "ss|zll"), &regex, &regex_len,
  436. &subject, &subject_len, &subpats, &flags, &start_offset) == FAILURE) {
  437. RETURN_FALSE;
  438. }
  439. /* Compile regex or get it from cache. */
  440. if ((pce = pcre_get_compiled_regex_cache(regex, regex_len TSRMLS_CC)) == NULL) {
  441. RETURN_FALSE;
  442. }
  443. php_pcre_match_impl(pce, subject, subject_len, return_value, subpats,
  444. global, ZEND_NUM_ARGS() >= 4, flags, start_offset TSRMLS_CC);
  445. }
  446. /* }}} */
  447. /* {{{ php_pcre_match_impl() */
  448. PHPAPI void php_pcre_match_impl(pcre_cache_entry *pce, char *subject, int subject_len, zval *return_value,
  449. zval *subpats, int global, int use_flags, long flags, long start_offset TSRMLS_DC)
  450. {
  451. zval *result_set, /* Holds a set of subpatterns after
  452. a global match */
  453. **match_sets = NULL; /* An array of sets of matches for each
  454. subpattern after a global match */
  455. pcre_extra *extra = pce->extra;/* Holds results of studying */
  456. pcre_extra extra_data; /* Used locally for exec options */
  457. int exoptions = 0; /* Execution options */
  458. int count = 0; /* Count of matched subpatterns */
  459. int *offsets; /* Array of subpattern offsets */
  460. int num_subpats; /* Number of captured subpatterns */
  461. int size_offsets; /* Size of the offsets array */
  462. int matched; /* Has anything matched */
  463. int g_notempty = 0; /* If the match should not be empty */
  464. const char **stringlist; /* Holds list of subpatterns */
  465. char **subpat_names; /* Array for named subpatterns */
  466. int i, rc;
  467. int subpats_order; /* Order of subpattern matches */
  468. int offset_capture; /* Capture match offsets: yes/no */
  469. /* Overwrite the passed-in value for subpatterns with an empty array. */
  470. if (subpats != NULL) {
  471. zval_dtor(subpats);
  472. array_init(subpats);
  473. }
  474. subpats_order = global ? PREG_PATTERN_ORDER : 0;
  475. if (use_flags) {
  476. offset_capture = flags & PREG_OFFSET_CAPTURE;
  477. /*
  478. * subpats_order is pre-set to pattern mode so we change it only if
  479. * necessary.
  480. */
  481. if (flags & 0xff) {
  482. subpats_order = flags & 0xff;
  483. }
  484. if ((global && (subpats_order < PREG_PATTERN_ORDER || subpats_order > PREG_SET_ORDER)) ||
  485. (!global && subpats_order != 0)) {
  486. php_error_docref(NULL TSRMLS_CC, E_WARNING, "Invalid flags specified");
  487. return;
  488. }
  489. } else {
  490. offset_capture = 0;
  491. }
  492. /* Negative offset counts from the end of the string. */
  493. if (start_offset < 0) {
  494. start_offset = subject_len + start_offset;
  495. if (start_offset < 0) {
  496. start_offset = 0;
  497. }
  498. }
  499. if (extra == NULL) {
  500. extra_data.flags = PCRE_EXTRA_MATCH_LIMIT | PCRE_EXTRA_MATCH_LIMIT_RECURSION;
  501. extra = &extra_data;
  502. }
  503. extra->match_limit = PCRE_G(backtrack_limit);
  504. extra->match_limit_recursion = PCRE_G(recursion_limit);
  505. /* Calculate the size of the offsets array, and allocate memory for it. */
  506. rc = pcre_fullinfo(pce->re, extra, PCRE_INFO_CAPTURECOUNT, &num_subpats);
  507. if (rc < 0) {
  508. php_error_docref(NULL TSRMLS_CC, E_WARNING, "Internal pcre_fullinfo() error %d", rc);
  509. RETURN_FALSE;
  510. }
  511. num_subpats++;
  512. size_offsets = num_subpats * 3;
  513. /*
  514. * Build a mapping from subpattern numbers to their names. We will always
  515. * allocate the table, even though there may be no named subpatterns. This
  516. * avoids somewhat more complicated logic in the inner loops.
  517. */
  518. subpat_names = make_subpats_table(num_subpats, pce TSRMLS_CC);
  519. if (!subpat_names) {
  520. RETURN_FALSE;
  521. }
  522. offsets = (int *)safe_emalloc(size_offsets, sizeof(int), 0);
  523. /* Allocate match sets array and initialize the values. */
  524. if (global && subpats_order == PREG_PATTERN_ORDER) {
  525. match_sets = (zval **)safe_emalloc(num_subpats, sizeof(zval *), 0);
  526. for (i=0; i<num_subpats; i++) {
  527. ALLOC_ZVAL(match_sets[i]);
  528. array_init(match_sets[i]);
  529. INIT_PZVAL(match_sets[i]);
  530. }
  531. }
  532. matched = 0;
  533. PCRE_G(error_code) = PHP_PCRE_NO_ERROR;
  534. do {
  535. /* Execute the regular expression. */
  536. count = pcre_exec(pce->re, extra, subject, subject_len, start_offset,
  537. exoptions|g_notempty, offsets, size_offsets);
  538. /* the string was already proved to be valid UTF-8 */
  539. exoptions |= PCRE_NO_UTF8_CHECK;
  540. /* Check for too many substrings condition. */
  541. if (count == 0) {
  542. php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Matched, but too many substrings");
  543. count = size_offsets/3;
  544. }
  545. /* If something has matched */
  546. if (count > 0) {
  547. matched++;
  548. /* If subpatterns array has been passed, fill it in with values. */
  549. if (subpats != NULL) {
  550. /* Try to get the list of substrings and display a warning if failed. */
  551. if (pcre_get_substring_list(subject, offsets, count, &stringlist) < 0) {
  552. efree(subpat_names);
  553. efree(offsets);
  554. php_error_docref(NULL TSRMLS_CC, E_WARNING, "Get subpatterns list failed");
  555. RETURN_FALSE;
  556. }
  557. if (global) { /* global pattern matching */
  558. if (subpats_order == PREG_PATTERN_ORDER) {
  559. /* For each subpattern, insert it into the appropriate array. */
  560. for (i = 0; i < count; i++) {
  561. if (offset_capture) {
  562. add_offset_pair(match_sets[i], (char *)stringlist[i],
  563. offsets[(i<<1)+1] - offsets[i<<1], offsets[i<<1], NULL);
  564. } else {
  565. add_next_index_stringl(match_sets[i], (char *)stringlist[i],
  566. offsets[(i<<1)+1] - offsets[i<<1], 1);
  567. }
  568. }
  569. /*
  570. * If the number of captured subpatterns on this run is
  571. * less than the total possible number, pad the result
  572. * arrays with empty strings.
  573. */
  574. if (count < num_subpats) {
  575. for (; i < num_subpats; i++) {
  576. add_next_index_string(match_sets[i], "", 1);
  577. }
  578. }
  579. } else {
  580. /* Allocate the result set array */
  581. ALLOC_ZVAL(result_set);
  582. array_init(result_set);
  583. INIT_PZVAL(result_set);
  584. /* Add all the subpatterns to it */
  585. for (i = 0; i < count; i++) {
  586. if (offset_capture) {
  587. add_offset_pair(result_set, (char *)stringlist[i],
  588. offsets[(i<<1)+1] - offsets[i<<1], offsets[i<<1], subpat_names[i]);
  589. } else {
  590. if (subpat_names[i]) {
  591. add_assoc_stringl(result_set, subpat_names[i], (char *)stringlist[i],
  592. offsets[(i<<1)+1] - offsets[i<<1], 1);
  593. }
  594. add_next_index_stringl(result_set, (char *)stringlist[i],
  595. offsets[(i<<1)+1] - offsets[i<<1], 1);
  596. }
  597. }
  598. /* And add it to the output array */
  599. zend_hash_next_index_insert(Z_ARRVAL_P(subpats), &result_set, sizeof(zval *), NULL);
  600. }
  601. } else { /* single pattern matching */
  602. /* For each subpattern, insert it into the subpatterns array. */
  603. for (i = 0; i < count; i++) {
  604. if (offset_capture) {
  605. add_offset_pair(subpats, (char *)stringlist[i],
  606. offsets[(i<<1)+1] - offsets[i<<1],
  607. offsets[i<<1], subpat_names[i]);
  608. } else {
  609. if (subpat_names[i]) {
  610. add_assoc_stringl(subpats, subpat_names[i], (char *)stringlist[i],
  611. offsets[(i<<1)+1] - offsets[i<<1], 1);
  612. }
  613. add_next_index_stringl(subpats, (char *)stringlist[i],
  614. offsets[(i<<1)+1] - offsets[i<<1], 1);
  615. }
  616. }
  617. }
  618. pcre_free((void *) stringlist);
  619. }
  620. } else if (count == PCRE_ERROR_NOMATCH) {
  621. /* If we previously set PCRE_NOTEMPTY after a null match,
  622. this is not necessarily the end. We need to advance
  623. the start offset, and continue. Fudge the offset values
  624. to achieve this, unless we're already at the end of the string. */
  625. if (g_notempty != 0 && start_offset < subject_len) {
  626. offsets[0] = start_offset;
  627. offsets[1] = start_offset + 1;
  628. } else
  629. break;
  630. } else {
  631. pcre_handle_exec_error(count TSRMLS_CC);
  632. break;
  633. }
  634. /* If we have matched an empty string, mimic what Perl's /g options does.
  635. This turns out to be rather cunning. First we set PCRE_NOTEMPTY and try
  636. the match again at the same point. If this fails (picked up above) we
  637. advance to the next character. */
  638. g_notempty = (offsets[1] == offsets[0])? PCRE_NOTEMPTY | PCRE_ANCHORED : 0;
  639. /* Advance to the position right after the last full match */
  640. start_offset = offsets[1];
  641. } while (global);
  642. /* Add the match sets to the output array and clean up */
  643. if (global && subpats_order == PREG_PATTERN_ORDER) {
  644. for (i = 0; i < num_subpats; i++) {
  645. if (subpat_names[i]) {
  646. zend_hash_update(Z_ARRVAL_P(subpats), subpat_names[i],
  647. strlen(subpat_names[i])+1, &match_sets[i], sizeof(zval *), NULL);
  648. Z_ADDREF_P(match_sets[i]);
  649. }
  650. zend_hash_next_index_insert(Z_ARRVAL_P(subpats), &match_sets[i], sizeof(zval *), NULL);
  651. }
  652. efree(match_sets);
  653. }
  654. efree(offsets);
  655. efree(subpat_names);
  656. /* Did we encounter an error? */
  657. if (PCRE_G(error_code) == PHP_PCRE_NO_ERROR) {
  658. RETVAL_LONG(matched);
  659. } else {
  660. RETVAL_FALSE;
  661. }
  662. }
  663. /* }}} */
  664. /* {{{ proto int preg_match(string pattern, string subject [, array &subpatterns [, int flags [, int offset]]])
  665. Perform a Perl-style regular expression match */
  666. static PHP_FUNCTION(preg_match)
  667. {
  668. php_do_pcre_match(INTERNAL_FUNCTION_PARAM_PASSTHRU, 0);
  669. }
  670. /* }}} */
  671. /* {{{ proto int preg_match_all(string pattern, string subject, array &subpatterns [, int flags [, int offset]])
  672. Perform a Perl-style global regular expression match */
  673. static PHP_FUNCTION(preg_match_all)
  674. {
  675. php_do_pcre_match(INTERNAL_FUNCTION_PARAM_PASSTHRU, 1);
  676. }
  677. /* }}} */
  678. /* {{{ preg_get_backref
  679. */
  680. static int preg_get_backref(char **str, int *backref)
  681. {
  682. register char in_brace = 0;
  683. register char *walk = *str;
  684. if (walk[1] == 0)
  685. return 0;
  686. if (*walk == '$' && walk[1] == '{') {
  687. in_brace = 1;
  688. walk++;
  689. }
  690. walk++;
  691. if (*walk >= '0' && *walk <= '9') {
  692. *backref = *walk - '0';
  693. walk++;
  694. } else
  695. return 0;
  696. if (*walk && *walk >= '0' && *walk <= '9') {
  697. *backref = *backref * 10 + *walk - '0';
  698. walk++;
  699. }
  700. if (in_brace) {
  701. if (*walk == 0 || *walk != '}')
  702. return 0;
  703. else
  704. walk++;
  705. }
  706. *str = walk;
  707. return 1;
  708. }
  709. /* }}} */
  710. /* {{{ preg_do_repl_func
  711. */
  712. static int preg_do_repl_func(zval *function, char *subject, int *offsets, char **subpat_names, int count, char **result TSRMLS_DC)
  713. {
  714. zval *retval_ptr; /* Function return value */
  715. zval **args[1]; /* Argument to pass to function */
  716. zval *subpats; /* Captured subpatterns */
  717. int result_len; /* Return value length */
  718. int i;
  719. MAKE_STD_ZVAL(subpats);
  720. array_init(subpats);
  721. for (i = 0; i < count; i++) {
  722. if (subpat_names[i]) {
  723. add_assoc_stringl(subpats, subpat_names[i], &subject[offsets[i<<1]] , offsets[(i<<1)+1] - offsets[i<<1], 1);
  724. }
  725. add_next_index_stringl(subpats, &subject[offsets[i<<1]], offsets[(i<<1)+1] - offsets[i<<1], 1);
  726. }
  727. args[0] = &subpats;
  728. if (call_user_function_ex(EG(function_table), NULL, function, &retval_ptr, 1, args, 0, NULL TSRMLS_CC) == SUCCESS && retval_ptr) {
  729. convert_to_string_ex(&retval_ptr);
  730. *result = estrndup(Z_STRVAL_P(retval_ptr), Z_STRLEN_P(retval_ptr));
  731. result_len = Z_STRLEN_P(retval_ptr);
  732. zval_ptr_dtor(&retval_ptr);
  733. } else {
  734. if (!EG(exception)) {
  735. php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unable to call custom replacement function");
  736. }
  737. result_len = offsets[1] - offsets[0];
  738. *result = estrndup(&subject[offsets[0]], result_len);
  739. }
  740. zval_ptr_dtor(&subpats);
  741. return result_len;
  742. }
  743. /* }}} */
  744. /* {{{ preg_do_eval
  745. */
  746. static int preg_do_eval(char *eval_str, int eval_str_len, char *subject,
  747. int *offsets, int count, char **result TSRMLS_DC)
  748. {
  749. zval retval; /* Return value from evaluation */
  750. char *eval_str_end, /* End of eval string */
  751. *match, /* Current match for a backref */
  752. *esc_match, /* Quote-escaped match */
  753. *walk, /* Used to walk the code string */
  754. *segment, /* Start of segment to append while walking */
  755. walk_last; /* Last walked character */
  756. int match_len; /* Length of the match */
  757. int esc_match_len; /* Length of the quote-escaped match */
  758. int result_len; /* Length of the result of the evaluation */
  759. int backref; /* Current backref */
  760. char *compiled_string_description;
  761. smart_str code = {0};
  762. eval_str_end = eval_str + eval_str_len;
  763. walk = segment = eval_str;
  764. walk_last = 0;
  765. while (walk < eval_str_end) {
  766. /* If found a backreference.. */
  767. if ('\\' == *walk || '$' == *walk) {
  768. smart_str_appendl(&code, segment, walk - segment);
  769. if (walk_last == '\\') {
  770. code.c[code.len-1] = *walk++;
  771. segment = walk;
  772. walk_last = 0;
  773. continue;
  774. }
  775. segment = walk;
  776. if (preg_get_backref(&walk, &backref)) {
  777. if (backref < count) {
  778. /* Find the corresponding string match and substitute it
  779. in instead of the backref */
  780. match = subject + offsets[backref<<1];
  781. match_len = offsets[(backref<<1)+1] - offsets[backref<<1];
  782. if (match_len) {
  783. esc_match = php_addslashes_ex(match, match_len, &esc_match_len, 0, 1 TSRMLS_CC);
  784. } else {
  785. esc_match = match;
  786. esc_match_len = 0;
  787. }
  788. } else {
  789. esc_match = "";
  790. esc_match_len = 0;
  791. }
  792. smart_str_appendl(&code, esc_match, esc_match_len);
  793. segment = walk;
  794. /* Clean up and reassign */
  795. if (esc_match_len)
  796. efree(esc_match);
  797. continue;
  798. }
  799. }
  800. walk++;
  801. walk_last = walk[-1];
  802. }
  803. smart_str_appendl(&code, segment, walk - segment);
  804. smart_str_0(&code);
  805. compiled_string_description = zend_make_compiled_string_description("regexp code" TSRMLS_CC);
  806. /* Run the code */
  807. if (zend_eval_stringl(code.c, code.len, &retval, compiled_string_description TSRMLS_CC) == FAILURE) {
  808. efree(compiled_string_description);
  809. php_error_docref(NULL TSRMLS_CC,E_ERROR, "Failed evaluating code: %s%s", PHP_EOL, code.c);
  810. /* zend_error() does not return in this case */
  811. }
  812. efree(compiled_string_description);
  813. convert_to_string(&retval);
  814. /* Save the return value and its length */
  815. *result = estrndup(Z_STRVAL(retval), Z_STRLEN(retval));
  816. result_len = Z_STRLEN(retval);
  817. /* Clean up */
  818. zval_dtor(&retval);
  819. smart_str_free(&code);
  820. return result_len;
  821. }
  822. /* }}} */
  823. /* {{{ php_pcre_replace
  824. */
  825. PHPAPI char *php_pcre_replace(char *regex, int regex_len,
  826. char *subject, int subject_len,
  827. zval *replace_val, int is_callable_replace,
  828. int *result_len, int limit, int *replace_count TSRMLS_DC)
  829. {
  830. pcre_cache_entry *pce; /* Compiled regular expression */
  831. /* Compile regex or get it from cache. */
  832. if ((pce = pcre_get_compiled_regex_cache(regex, regex_len TSRMLS_CC)) == NULL) {
  833. return NULL;
  834. }
  835. return php_pcre_replace_impl(pce, subject, subject_len, replace_val,
  836. is_callable_replace, result_len, limit, replace_count TSRMLS_CC);
  837. }
  838. /* }}} */
  839. /* {{{ php_pcre_replace_impl() */
  840. PHPAPI char *php_pcre_replace_impl(pcre_cache_entry *pce, char *subject, int subject_len, zval *replace_val,
  841. int is_callable_replace, int *result_len, int limit, int *replace_count TSRMLS_DC)
  842. {
  843. pcre_extra *extra = pce->extra;/* Holds results of studying */
  844. pcre_extra extra_data; /* Used locally for exec options */
  845. int exoptions = 0; /* Execution options */
  846. int count = 0; /* Count of matched subpatterns */
  847. int *offsets; /* Array of subpattern offsets */
  848. char **subpat_names; /* Array for named subpatterns */
  849. int num_subpats; /* Number of captured subpatterns */
  850. int size_offsets; /* Size of the offsets array */
  851. int new_len; /* Length of needed storage */
  852. int alloc_len; /* Actual allocated length */
  853. int eval_result_len=0; /* Length of the eval'ed or
  854. function-returned string */
  855. int match_len; /* Length of the current match */
  856. int backref; /* Backreference number */
  857. int eval; /* If the replacement string should be eval'ed */
  858. int start_offset; /* Where the new search starts */
  859. int g_notempty=0; /* If the match should not be empty */
  860. int replace_len=0; /* Length of replacement string */
  861. char *result, /* Result of replacement */
  862. *replace=NULL, /* Replacement string */
  863. *new_buf, /* Temporary buffer for re-allocation */
  864. *walkbuf, /* Location of current replacement in the result */
  865. *walk, /* Used to walk the replacement string */
  866. *match, /* The current match */
  867. *piece, /* The current piece of subject */
  868. *replace_end=NULL, /* End of replacement string */
  869. *eval_result, /* Result of eval or custom function */
  870. walk_last; /* Last walked character */
  871. int rc;
  872. if (extra == NULL) {
  873. extra_data.flags = PCRE_EXTRA_MATCH_LIMIT | PCRE_EXTRA_MATCH_LIMIT_RECURSION;
  874. extra = &extra_data;
  875. }
  876. extra->match_limit = PCRE_G(backtrack_limit);
  877. extra->match_limit_recursion = PCRE_G(recursion_limit);
  878. eval = pce->preg_options & PREG_REPLACE_EVAL;
  879. if (is_callable_replace) {
  880. if (eval) {
  881. php_error_docref(NULL TSRMLS_CC, E_WARNING, "Modifier /e cannot be used with replacement callback");
  882. return NULL;
  883. }
  884. } else {
  885. replace = Z_STRVAL_P(replace_val);
  886. replace_len = Z_STRLEN_P(replace_val);
  887. replace_end = replace + replace_len;
  888. }
  889. /* Calculate the size of the offsets array, and allocate memory for it. */
  890. rc = pcre_fullinfo(pce->re, extra, PCRE_INFO_CAPTURECOUNT, &num_subpats);
  891. if (rc < 0) {
  892. php_error_docref(NULL TSRMLS_CC, E_WARNING, "Internal pcre_fullinfo() error %d", rc);
  893. return NULL;
  894. }
  895. num_subpats++;
  896. size_offsets = num_subpats * 3;
  897. /*
  898. * Build a mapping from subpattern numbers to their names. We will always
  899. * allocate the table, even though there may be no named subpatterns. This
  900. * avoids somewhat more complicated logic in the inner loops.
  901. */
  902. subpat_names = make_subpats_table(num_subpats, pce TSRMLS_CC);
  903. if (!subpat_names) {
  904. return NULL;
  905. }
  906. offsets = (int *)safe_emalloc(size_offsets, sizeof(int), 0);
  907. alloc_len = 2 * subject_len + 1;
  908. result = safe_emalloc(alloc_len, sizeof(char), 0);
  909. /* Initialize */
  910. match = NULL;
  911. *result_len = 0;
  912. start_offset = 0;
  913. PCRE_G(error_code) = PHP_PCRE_NO_ERROR;
  914. while (1) {
  915. /* Execute the regular expression. */
  916. count = pcre_exec(pce->re, extra, subject, subject_len, start_offset,
  917. exoptions|g_notempty, offsets, size_offsets);
  918. /* the string was already proved to be valid UTF-8 */
  919. exoptions |= PCRE_NO_UTF8_CHECK;
  920. /* Check for too many substrings condition. */
  921. if (count == 0) {
  922. php_error_docref(NULL TSRMLS_CC,E_NOTICE, "Matched, but too many substrings");
  923. count = size_offsets/3;
  924. }
  925. piece = subject + start_offset;
  926. if (count > 0 && (limit == -1 || limit > 0)) {
  927. if (replace_count) {
  928. ++*replace_count;
  929. }
  930. /* Set the match location in subject */
  931. match = subject + offsets[0];
  932. new_len = *result_len + offsets[0] - start_offset; /* part before the match */
  933. /* If evaluating, do it and add the return string's length */
  934. if (eval) {
  935. eval_result_len = preg_do_eval(replace, replace_len, subject,
  936. offsets, count, &eval_result TSRMLS_CC);
  937. new_len += eval_result_len;
  938. } else if (is_callable_replace) {
  939. /* Use custom function to get replacement string and its length. */
  940. eval_result_len = preg_do_repl_func(replace_val, subject, offsets, subpat_names, count, &eval_result TSRMLS_CC);
  941. new_len += eval_result_len;
  942. } else { /* do regular substitution */
  943. walk = replace;
  944. walk_last = 0;
  945. while (walk < replace_end) {
  946. if ('\\' == *walk || '$' == *walk) {
  947. if (walk_last == '\\') {
  948. walk++;
  949. walk_last = 0;
  950. continue;
  951. }
  952. if (preg_get_backref(&walk, &backref)) {
  953. if (backref < count)
  954. new_len += offsets[(backref<<1)+1] - offsets[backref<<1];
  955. continue;
  956. }
  957. }
  958. new_len++;
  959. walk++;
  960. walk_last = walk[-1];
  961. }
  962. }
  963. if (new_len + 1 > alloc_len) {
  964. alloc_len = 1 + alloc_len + 2 * new_len;
  965. new_buf = emalloc(alloc_len);
  966. memcpy(new_buf, result, *result_len);
  967. efree(result);
  968. result = new_buf;
  969. }
  970. /* copy the part of the string before the match */
  971. memcpy(&result[*result_len], piece, match-piece);
  972. *result_len += match-piece;
  973. /* copy replacement and backrefs */
  974. walkbuf = result + *result_len;
  975. /* If evaluating or using custom function, copy result to the buffer
  976. * and clean up. */
  977. if (eval || is_callable_replace) {
  978. memcpy(walkbuf, eval_result, eval_result_len);
  979. *result_len += eval_result_len;
  980. STR_FREE(eval_result);
  981. } else { /* do regular backreference copying */
  982. walk = replace;
  983. walk_last = 0;
  984. while (walk < replace_end) {
  985. if ('\\' == *walk || '$' == *walk) {
  986. if (walk_last == '\\') {
  987. *(walkbuf-1) = *walk++;
  988. walk_last = 0;
  989. continue;
  990. }
  991. if (preg_get_backref(&walk, &backref)) {
  992. if (backref < count) {
  993. match_len = offsets[(backref<<1)+1] - offsets[backref<<1];
  994. memcpy(walkbuf, subject + offsets[backref<<1], match_len);
  995. walkbuf += match_len;
  996. }
  997. continue;
  998. }
  999. }
  1000. *walkbuf++ = *walk++;
  1001. walk_last = walk[-1];
  1002. }
  1003. *walkbuf = '\0';
  1004. /* increment the result length by how much we've added to the string */
  1005. *result_len += walkbuf - (result + *result_len);
  1006. }
  1007. if (limit != -1)
  1008. limit--;
  1009. } else if (count == PCRE_ERROR_NOMATCH || limit == 0) {
  1010. /* If we previously set PCRE_NOTEMPTY after a null match,
  1011. this is not necessarily the end. We need to advance
  1012. the start offset, and continue. Fudge the offset values
  1013. to achieve this, unless we're already at the end of the string. */
  1014. if (g_notempty != 0 && start_offset < subject_len) {
  1015. offsets[0] = start_offset;
  1016. offsets[1] = start_offset + 1;
  1017. memcpy(&result[*result_len], piece, 1);
  1018. (*result_len)++;
  1019. } else {
  1020. new_len = *result_len + subject_len - start_offset;
  1021. if (new_len + 1 > alloc_len) {
  1022. alloc_len = new_len + 1; /* now we know exactly how long it is */
  1023. new_buf = safe_emalloc(alloc_len, sizeof(char), 0);
  1024. memcpy(new_buf, result, *result_len);
  1025. efree(result);
  1026. result = new_buf;
  1027. }
  1028. /* stick that last bit of string on our output */
  1029. memcpy(&result[*result_len], piece, subject_len - start_offset);
  1030. *result_len += subject_len - start_offset;
  1031. result[*result_len] = '\0';
  1032. break;
  1033. }
  1034. } else {
  1035. pcre_handle_exec_error(count TSRMLS_CC);
  1036. efree(result);
  1037. result = NULL;
  1038. break;
  1039. }
  1040. /* If we have matched an empty string, mimic what Perl's /g options does.
  1041. This turns out to be rather cunning. First we set PCRE_NOTEMPTY and try
  1042. the match again at the same point. If this fails (picked up above) we
  1043. advance to the next character. */
  1044. g_notempty = (offsets[1] == offsets[0])? PCRE_NOTEMPTY | PCRE_ANCHORED : 0;
  1045. /* Advance to the next piece. */
  1046. start_offset = offsets[1];
  1047. }
  1048. efree(offsets);
  1049. efree(subpat_names);
  1050. return result;
  1051. }
  1052. /* }}} */
  1053. /* {{{ php_replace_in_subject
  1054. */
  1055. static char *php_replace_in_subject(zval *regex, zval *replace, zval **subject, int *result_len, int limit, int is_callable_replace, int *replace_count TSRMLS_DC)
  1056. {
  1057. zval **regex_entry,
  1058. **replace_entry = NULL,
  1059. *replace_value,
  1060. empty_replace;
  1061. char *subject_value,
  1062. *result;
  1063. int subject_len;
  1064. /* Make sure we're dealing with strings. */
  1065. convert_to_string_ex(subject);
  1066. /* FIXME: This might need to be changed to STR_EMPTY_ALLOC(). Check if this zval could be dtor()'ed somehow */
  1067. ZVAL_STRINGL(&empty_replace, "", 0, 0);
  1068. /* If regex is an array */
  1069. if (Z_TYPE_P(regex) == IS_ARRAY) {
  1070. /* Duplicate subject string for repeated replacement */
  1071. subject_value = estrndup(Z_STRVAL_PP(subject), Z_STRLEN_PP(subject));
  1072. subject_len = Z_STRLEN_PP(subject);
  1073. *result_len = subject_len;
  1074. zend_hash_internal_pointer_reset(Z_ARRVAL_P(regex));
  1075. replace_value = replace;
  1076. if (Z_TYPE_P(replace) == IS_ARRAY && !is_callable_replace)
  1077. zend_hash_internal_pointer_reset(Z_ARRVAL_P(replace));
  1078. /* For each entry in the regex array, get the entry */
  1079. while (zend_hash_get_current_data(Z_ARRVAL_P(regex), (void **)&regex_entry) == SUCCESS) {
  1080. /* Make sure we're dealing with strings. */
  1081. convert_to_string_ex(regex_entry);
  1082. /* If replace is an array and not a callable construct */
  1083. if (Z_TYPE_P(replace) == IS_ARRAY && !is_callable_replace) {
  1084. /* Get current entry */
  1085. if (zend_hash_get_current_data(Z_ARRVAL_P(replace), (void **)&replace_entry) == SUCCESS) {
  1086. if (!is_callable_replace) {
  1087. convert_to_string_ex(replace_entry);
  1088. }
  1089. replace_value = *replace_entry;
  1090. zend_hash_move_forward(Z_ARRVAL_P(replace));
  1091. } else {
  1092. /* We've run out of replacement strings, so use an empty one */
  1093. replace_value = &empty_replace;
  1094. }
  1095. }
  1096. /* Do the actual replacement and put the result back into subject_value
  1097. for further replacements. */
  1098. if ((result = php_pcre_replace(Z_STRVAL_PP(regex_entry),
  1099. Z_STRLEN_PP(regex_entry),
  1100. subject_value,
  1101. subject_len,
  1102. replace_value,
  1103. is_callable_replace,
  1104. result_len,
  1105. limit,
  1106. replace_count TSRMLS_CC)) != NULL) {
  1107. efree(subject_value);
  1108. subject_value = result;
  1109. subject_len = *result_len;
  1110. } else {
  1111. efree(subject_value);
  1112. return NULL;
  1113. }
  1114. zend_hash_move_forward(Z_ARRVAL_P(regex));
  1115. }
  1116. return subject_value;
  1117. } else {
  1118. result = php_pcre_replace(Z_STRVAL_P(regex),
  1119. Z_STRLEN_P(regex),
  1120. Z_STRVAL_PP(subject),
  1121. Z_STRLEN_PP(subject),
  1122. replace,
  1123. is_callable_replace,
  1124. result_len,
  1125. limit,
  1126. replace_count TSRMLS_CC);
  1127. return result;
  1128. }
  1129. }
  1130. /* }}} */
  1131. /* {{{ preg_replace_impl
  1132. */
  1133. static void preg_replace_impl(INTERNAL_FUNCTION_PARAMETERS, int is_callable_replace, int is_filter)
  1134. {
  1135. zval **regex,
  1136. **replace,
  1137. **subject,
  1138. **subject_entry,
  1139. **zcount = NULL;
  1140. char *result;
  1141. int result_len;
  1142. int limit_val = -1;
  1143. long limit = -1;
  1144. char *string_key;
  1145. ulong num_key;
  1146. char *callback_name;
  1147. int replace_count=0, old_replace_count;
  1148. /* Get function parameters and do error-checking. */
  1149. if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "ZZZ|lZ", &regex, &replace, &subject, &limit, &zcount) == FAILURE) {
  1150. return;
  1151. }
  1152. if (!is_callable_replace && Z_TYPE_PP(replace) == IS_ARRAY && Z_TYPE_PP(regex) != IS_ARRAY) {
  1153. php_error_docref(NULL TSRMLS_CC, E_WARNING, "Parameter mismatch, pattern is a string while replacement is an array");
  1154. RETURN_FALSE;
  1155. }
  1156. SEPARATE_ZVAL(replace);
  1157. if (Z_TYPE_PP(replace) != IS_ARRAY && (Z_TYPE_PP(replace) != IS_OBJECT || !is_callable_replace)) {
  1158. convert_to_string_ex(replace);
  1159. }
  1160. if (is_callable_replace) {
  1161. if (!zend_is_callable(*replace, 0, &callback_name TSRMLS_CC)) {
  1162. php_error_docref(NULL TSRMLS_CC, E_WARNING, "Requires argument 2, '%s', to be a valid callback", callback_name);
  1163. efree(callback_name);
  1164. MAKE_COPY_ZVAL(subject, return_value);
  1165. return;
  1166. }
  1167. efree(callback_name);
  1168. }
  1169. SEPARATE_ZVAL(regex);
  1170. SEPARATE_ZVAL(subject);
  1171. if (ZEND_NUM_ARGS() > 3) {
  1172. limit_val = limit;
  1173. }
  1174. if (Z_TYPE_PP(regex) != IS_ARRAY)
  1175. convert_to_string_ex(regex);
  1176. /* if subject is an array */
  1177. if (Z_TYPE_PP(subject) == IS_ARRAY) {
  1178. array_init(return_value);
  1179. zend_hash_internal_pointer_reset(Z_ARRVAL_PP(subject));
  1180. /* For each subject entry, convert it to string, then perform replacement
  1181. and add the result to the return_value array. */
  1182. while (zend_hash_get_current_data(Z_ARRVAL_PP(subject), (void **)&subject_entry) == SUCCESS) {
  1183. SEPARATE_ZVAL(subject_entry);
  1184. old_replace_count = replace_count;
  1185. if ((result = php_replace_in_subject(*regex, *replace, subject_entry, &result_len, limit_val, is_callable_replace, &replace_count TSRMLS_CC)) != NULL) {
  1186. if (!is_filter || replace_count > old_replace_count) {
  1187. /* Add to return array */
  1188. switch(zend_hash_get_current_key(Z_ARRVAL_PP(subject), &string_key, &num_key, 0))
  1189. {
  1190. case HASH_KEY_IS_STRING:
  1191. add_assoc_stringl(return_value, string_key, result, result_len, 0);
  1192. break;
  1193. case HASH_KEY_IS_LONG:
  1194. add_index_stringl(return_value, num_key, result, result_len, 0);
  1195. break;
  1196. }
  1197. } else {
  1198. efree(result);
  1199. }
  1200. }
  1201. zend_hash_move_forward(Z_ARRVAL_PP(subject));
  1202. }
  1203. } else { /* if subject is not an array */
  1204. old_replace_count = replace_count;
  1205. if ((result = php_replace_in_subject(*regex, *replace, subject, &result_len, limit_val, is_callable_replace, &replace_count TSRMLS_CC)) != NULL) {
  1206. if (!is_filter || replace_count > old_replace_count) {
  1207. RETVAL_STRINGL(result, result_len, 0);
  1208. } else {
  1209. efree(result);
  1210. }
  1211. }
  1212. }
  1213. if (ZEND_NUM_ARGS() > 4) {
  1214. zval_dtor(*zcount);
  1215. ZVAL_LONG(*zcount, replace_count);
  1216. }
  1217. }
  1218. /* }}} */
  1219. /* {{{ proto mixed preg_replace(mixed regex, mixed replace, mixed subject [, int limit [, int &count]])
  1220. Perform Perl-style regular expression replacement. */
  1221. static PHP_FUNCTION(preg_replace)
  1222. {
  1223. preg_replace_impl(INTERNAL_FUNCTION_PARAM_PASSTHRU, 0, 0);
  1224. }
  1225. /* }}} */
  1226. /* {{{ proto mixed preg_replace_callback(mixed regex, mixed callback, mixed subject [, int limit [, int &count]])
  1227. Perform Perl-style regular expression replacement using replacement callback. */
  1228. static PHP_FUNCTION(preg_replace_callback)
  1229. {
  1230. preg_replace_impl(INTERNAL_FUNCTION_PARAM_PASSTHRU, 1, 0);
  1231. }
  1232. /* }}} */
  1233. /* {{{ proto mixed preg_filter(mixed regex, mixed replace, mixed subject [, int limit [, int &count]])
  1234. Perform Perl-style regular expression replacement and only return matches. */
  1235. static PHP_FUNCTION(preg_filter)
  1236. {
  1237. preg_replace_impl(INTERNAL_FUNCTION_PARAM_PASSTHRU, 0, 1);
  1238. }
  1239. /* }}} */
  1240. /* {{{ proto array preg_split(string pattern, string subject [, int limit [, int flags]])
  1241. Split string into an array using a perl-style regular expression as a delimiter */
  1242. static PHP_FUNCTION(preg_split)
  1243. {
  1244. char *regex; /* Regular expression */
  1245. char *subject; /* String to match against */
  1246. int regex_len;
  1247. int subject_len;
  1248. long limit_val = -1;/* Integer value of limit */
  1249. long flags = 0; /* Match control flags */
  1250. pcre_cache_entry *pce; /* Compiled regular expression */
  1251. /* Get function parameters and do error checking */
  1252. if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "ss|ll", &regex, &regex_len,
  1253. &subject, &subject_len, &limit_val, &flags) == FAILURE) {
  1254. RETURN_FALSE;
  1255. }
  1256. /* Compile regex or get it from cache. */
  1257. if ((pce = pcre_get_compiled_regex_cache(regex, regex_len TSRMLS_CC)) == NULL) {
  1258. RETURN_FALSE;
  1259. }
  1260. php_pcre_split_impl(pce, subject, subject_len, return_value, limit_val, flags TSRMLS_CC);
  1261. }
  1262. /* }}} */
  1263. /* {{{ php_pcre_split
  1264. */
  1265. PHPAPI void php_pcre_split_impl(pcre_cache_entry *pce, char *subject, int subject_len, zval *return_value,
  1266. long limit_val, long flags TSRMLS_DC)
  1267. {
  1268. pcre_extra *extra = NULL; /* Holds results of studying */
  1269. pcre *re_bump = NULL; /* Regex instance for empty matches */
  1270. pcre_extra *extra_bump = NULL; /* Almost dummy */
  1271. pcre_extra extra_data; /* Used locally for exec options */
  1272. int *offsets; /* Array of subpattern offsets */
  1273. int size_offsets; /* Size of the offsets array */
  1274. int exoptions = 0; /* Execution options */
  1275. int count = 0; /* Count of matched subpatterns */
  1276. int start_offset; /* Where the new search starts */
  1277. int next_offset; /* End of the last delimiter match + 1 */
  1278. int g_notempty = 0; /* If the match should not be empty */
  1279. char *last_match; /* Location of last match */
  1280. int rc;
  1281. int no_empty; /* If NO_EMPTY flag is set */
  1282. int delim_capture; /* If delimiters should be captured */
  1283. int offset_capture; /* If offsets should be captured */
  1284. no_empty = flags & PREG_SPLIT_NO_EMPTY;
  1285. delim_capture = flags & PREG_SPLIT_DELIM_CAPTURE;
  1286. offset_capture = flags & PREG_SPLIT_OFFSET_CAPTURE;
  1287. if (limit_val == 0) {
  1288. limit_val = -1;
  1289. }
  1290. if (extra == NULL) {
  1291. extra_data.flags = PCRE_EXTRA_MATCH_LIMIT | PCRE_EXTRA_MATCH_LIMIT_RECURSION;
  1292. extra = &extra_data;
  1293. }
  1294. extra->match_limit = PCRE_G(backtrack_limit);
  1295. extra->match_limit_recursion = PCRE_G(recursion_limit);
  1296. /* Initialize return value */
  1297. array_init(return_value);
  1298. /* Calculate the size of the offsets array, and allocate memory for it. */
  1299. rc = pcre_fullinfo(pce->re, extra, PCRE_INFO_CAPTURECOUNT, &size_offsets);
  1300. if (rc < 0) {
  1301. php_error_docref(NULL TSRMLS_CC, E_WARNING, "Internal pcre_fullinfo() error %d", rc);
  1302. RETURN_FALSE;
  1303. }
  1304. size_offsets = (size_offsets + 1) * 3;
  1305. offsets = (int *)safe_emalloc(size_offsets, sizeof(int), 0);
  1306. /* Start at the beginning of the string */
  1307. start_offset = 0;
  1308. next_offset = 0;
  1309. last_match = subject;
  1310. PCRE_G(error_code) = PHP_PCRE_NO_ERROR;
  1311. /* Get next piece if no limit or limit not yet reached and something matched*/
  1312. while ((limit_val == -1 || limit_val > 1)) {
  1313. count = pcre_exec(pce->re, extra, subject,
  1314. subject_len, start_offset,
  1315. exoptions|g_notempty, offsets, size_offsets);
  1316. /* the string was already proved to be valid UTF-8 */
  1317. exoptions |= PCRE_NO_UTF8_CHECK;
  1318. /* Check for too many substrings condition. */
  1319. if (count == 0) {
  1320. php_error_docref(NULL TSRMLS_CC,E_NOTICE, "Matched, but too many substrings");
  1321. count = size_offsets/3;
  1322. }
  1323. /* If something matched */
  1324. if (count > 0) {
  1325. if (!no_empty || &subject[offsets[0]] != last_match) {
  1326. if (offset_capture) {
  1327. /* Add (match, offset) pair to the return value */
  1328. add_offset_pair(return_value, last_match, &subject[offsets[0]]-last_match, next_offset, NULL);
  1329. } else {
  1330. /* Add the piece to the return value */
  1331. add_next_index_stringl(return_value, last_match,
  1332. &subject[offsets[0]]-last_match, 1);
  1333. }
  1334. /* One less left to do */
  1335. if (limit_val != -1)
  1336. limit_val--;
  1337. }
  1338. last_match = &subject[offsets[1]];
  1339. next_offset = offsets[1];
  1340. if (delim_capture) {
  1341. int i, match_len;
  1342. for (i = 1; i < count; i++) {
  1343. match_len = offsets[(i<<1)+1] - offsets[i<<1];
  1344. /* If we have matched a delimiter */
  1345. if (!no_empty || match_len > 0) {
  1346. if (offset_capture) {
  1347. add_offset_pair(return_value, &subject[offsets[i<<1]], match_len, offsets[i<<1], NULL);
  1348. } else {
  1349. add_next_index_stringl(return_value,
  1350. &subject[offsets[i<<1]],
  1351. match_len, 1);
  1352. }
  1353. }
  1354. }
  1355. }
  1356. } else if (count == PCRE_ERROR_NOMATCH) {
  1357. /* If we previously set PCRE_NOTEMPTY after a null match,
  1358. this is not necessarily the end. We need to advance
  1359. the start offset, and continue. Fudge the offset values
  1360. to achieve this, unless we're already at the end of the string. */
  1361. if (g_notempty != 0 && start_offset < subject_len) {
  1362. if (pce->compile_options & PCRE_UTF8) {
  1363. if (re_bump == NULL) {
  1364. int dummy;
  1365. if ((re_bump = pcre_get_compiled_regex("/./us", &extra_bump, &dummy TSRMLS_CC)) == NULL) {
  1366. RETURN_FALSE;
  1367. }
  1368. }
  1369. count = p

Large files files are truncated, but you can click here to view the full file