Home  >  Article  >  Backend Development  >  PHP code that intercepts strings and retains complete xml tags

PHP code that intercepts strings and retains complete xml tags

WBOY
WBOYOriginal
2016-07-25 09:05:41885browse
  1. /**
  2. * author: goosman
  3. * blog: http://blog.csdn.net/lgg201
  4. * mail: lgg860911@yahoo.com.cn
  5. */
  6. $str = '01234567890120123456789';
  7. function substr_remain_tag($s, $o, $l) {
  8. $is_match = preg_match_all(<< ;
  9. #This regular expression parses xml tags. The tag attribute internally supports the escape character "", and supports the escaping of "" itself and the corresponding quotation marks
  10. <( w+) #Start of tag
  11. (?: #Attribute list
  12. s+ #Preceding space
  13. w+ #Attribute name
  14. s* #Blank after attribute name (for compatibility)
  15. = #Equal sign between attribute name values
  16. s* #Blank before attribute value (for compatibility)
  17. (?: #Attribute value (quote processing)
  18. " #Double quote situation
  19. (?:
  20. \\\\ #Eat two consecutive escape characters (indicates escape symbol itself)
  21. |
  22. \\" #Eat the escape character followed by a quote (representing an escaped quote)
  23. |
  24. [^"\\]* #Other characters
  25. )*
  26. "
  27. |
  28. ' #Single quote Case
  29. (?:
  30. \\\\ #Eat two consecutive escape characters (representing the escape character itself)
  31. |
  32. \\' #Eat the escape character followed by a quote (representing the escaped quote)
  33. |
  34. [^'\\]* #Other characters
  35. )*
  36. '
  37. )
  38. )*
  39. >
  40. .*? #Tag content
  41. #End tag
  42. ;x
  43. heredoc
  44. , $s, $matches, PREG_OFFSET_CAPTURE, $o);
  45. if ( $is_match ) {
  46. foreach ( $matches[0] as $match ) {
  47. $o0 = $match[1];
  48. #The label left boundary is intercepted when it crosses Right boundary of the target, exit
  49. if ( $o0 >= $o + $l ) break;
  50. $l0 = strlen($match[0]);
  51. #The right boundary of the label is within the right boundary of the intercepted target, continue
  52. if ( $o0 + $l0 < $o + $l ) continue;
  53. #The following is label cross-border processing
  54. $l = $o0 + $l0 - $o;
  55. break;
  56. }
  57. }
  58. return substr($s , $o, $l);
  59. }
  60. echo $str . chr(10);
  61. echo substr_remain_tag($str, 0, 20) . chr(10);
Copy code


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn