search
HomeBackend DevelopmentPHP TutorialPHP keyword replacement class (avoid repeated replacement, retain and restore the original link)

  1. /*

  2. * Keyword matching class
  3. * @author ylx
  4. * @packet mipang
  5. * Usage examples
  6. * $str = "The green-shelled laying hen spreads Van der Sar next year, and the next year 1 spreads open the room Lucas local army";
  7. * $key = new KeyReplace($str,array("xxxx"=>"sadf", "Next year 1" =>'http://baidu.com',"Next year" =>'google.com'));
  8. * echo $key->getResultText();
  9. * echo $key->getRuntime();
  10. */
  11. class KeyReplace
  12. {
  13. private $keys = array();
  14. private $text = "";
  15. private $runtime = 0;
  16. private $url = true;
  17. private $stopkeys = array();
  18. private $all = false;
  19. /**
  20. * @access public
  21. * @param string $text specifies the article to be processed
  22. * @param array $keys specifies the dictionary phrase array(key=>url,...) url can be an array, if it is an array it will be replaced randomly One of them
  23. * @param array $stopkeys specifies stop words array(key,...) The words in this will not be processed
  24. * @param boolean $url true means to replace it with a link, otherwise it will only be replaced
  25. * @param boolean $all true means replace all found words, otherwise only replace the first time
  26. */
  27. public function __construct($text='',$keys=array(),$url=true,$stopkeys=array (),$all=false) {
  28. $this->keys = $keys;
  29. $this->text = $text;
  30. $this->url = $url;
  31. $this->stopkeys = $stopkeys;
  32. $this->all = $all;
  33. }
  34. /**

  35. * Get the processed article
  36. * @access public
  37. * @return string text
  38. */
  39. public function getResultText() {
  40. $start = microtime(true);
  41. $keys = $this->hits_keys();
  42. $keys_tmp = array_keys($keys);

  43. function cmp($a, $b ){

  44. if (mb_strlen($a) == mb_strlen($b)) {
  45. return 0;
  46. }
  47. return (mb_strlen($a) }< ;/p>
  48. usort($keys_tmp,"cmp");

  49. foreach($keys_tmp as $key){

  50. if( is_array($keys[$key])){

  51. $url = $keys[$key][rand(0,count($keys[$key])-1)];
  52. }else
  53. $url = $keys[ $key];
  54. $this->text = $this->r_s($this->text,$key,$url);

  55. }
  56. $this->runtime = microtime(true)-$start;
  57. return $this->text;

  58. }
  59. /**
  60. * Get processing time
  61. * @access public
  62. * @return float
  63. */
  64. public function getRuntime() {
  65. return $this->runtime;

  66. }

  67. /**

  68. * Set keywords
  69. * @access public
  70. * @param array $keys array(key=>url,...)
  71. */
  72. public function setKeys($keys) {
  73. $this->keys = $keys;

  74. }

  75. /**
  76. * Set stop words
  77. * @access public
  78. * @param array $keys array(key,...)
  79. * /
  80. public function setStopKeys($keys) {
  81. $this->stopkeys = $keys;

  82. }

  83. /**
  84. * Set article
  85. * @access public
  86. * @param string $text
  87. */
  88. public function setText($text) {
  89. $this->text = $text;

  90. }

  91. /**

  92. * Used to find the hit keywords in the string
  93. * @access public
  94. * @return array $keys Returns the matched word array(key=>url,...)
  95. */
  96. public function hits_keys(){
  97. $ar = $this->keys;
  98. $ar = $ar?$ar:array();
  99. $result=array();
  100. $ str = $this->text;
  101. foreach($ar as $k=>$url){
  102. $k = trim($k);
  103. if(!$k)
  104. continue;
  105. if(strpos($ str,$k)!==false && !in_array($k,$this->stopkeys)){
  106. $result[$k] = $url;
  107. }
  108. }
  109. return $result?$result:array( );
  110. }
  111. /**

  112. * Used to find the hit stop words in the string
  113. * @access public
  114. * @return array $keys Returns the matched word array(key,...)
  115. */
  116. public function hits_stop_keys(){
  117. $ar = $this->stopkeys;
  118. $ar = $ar?$ar:array();
  119. $result=array();
  120. $str = $this->text;
  121. foreach($ar as $k){
  122. $k = trim($k);
  123. if(!$k)
  124. continue;
  125. if(strpos($str,$k)!==false && in_array($k,$this->stopkeys)){
  126. $result[] = $k;
  127. }
  128. }
  129. return $result?$result:array();
  130. }
  131. /**

  132. * Handle the replacement process
  133. * @access private
  134. * @param string $text The person being replaced
  135. * @param string $key Keywords
  136. * @param string $url Link
  137. * @return string $text The processed article
  138. */
  139. private function r_s($text,$key,$url){
  140. $tmp = $text;

  141. $stop_keys = $this->hits_stop_keys();

  142. $stopkeys = $tags = $a = array();

  143. if(preg_match_all("#]+>[^]*>#su",$tmp,$m)){
  144. $a=$m[0];
  145. foreach($m[0] as $k=>$z){

  146. $z = preg_replace("###s","#",$z);
  147. $tmp = preg_replace('#'.$z.'#s',"[_a".$k."_]",$tmp,1);

  148. }
  149. };

  150. if(preg_match_all("#]+>#s",$tmp,$m)){

  151. $tags = $m[0];
  152. foreach($m[0] as $k=>$z){
  153. $z = preg_replace("###s","#",$z);
  154. $tmp = preg_replace('#'.$z.'#s',"[_tag".$k."_]",$tmp,1);
  155. }
  156. }
  157. if(!empty($stop_keys)){
  158. if(preg_match_all("#".implode("|",$stop_keys)."#s",$tmp,$m)){
  159. $stopkeys = $m[0];
  160. foreach($m[0] as $k=>$z){
  161. $z = preg_replace("###s","#",$z);
  162. $tmp = preg_replace('#'.$z.'#s',"[_s".$k."_]",$tmp,1);
  163. }
  164. }
  165. }
  166. $key1 = preg_replace("#([#()[]*])#s","\\$1",$key);
  167. if($this->url)

  168. $tmp = preg_replace("#(?![_s|[_a|[_|[_t|[_ta|[_tag)".$key1."(?!agd+_]|gd+_]|d+_]|sd+_]|_])#us",''.$key.'',$tmp,$this->all?-1:1);
  169. else
  170. $tmp = preg_replace("#(?![_s|[_a|[_|[_t|[_ta|[_tag)".$key1."(?!agd+_]|gd+_]|d+_]|sd+_]|_])#us",$url,$tmp,$this->all?-1:1);
  171. if(!empty($a)){

  172. foreach($a as $n=>$at){

  173. $tmp = str_replace("[_a".$n."_]",$at,$tmp);

  174. }

  175. }

  176. if(!empty($tags)){
  177. foreach($tags as $n=>$at){

  178. $tmp = str_replace("[_tag".$n."_]",$at,$tmp);

  179. }

  180. }

  181. if(!empty($stopkeys)){
  182. foreach($stopkeys as $n=>$at){

  183. $tmp = str_replace("[_s".$n."_]",$at,$tmp);

  184. }

  185. }

  186. return $tmp;
  187. }
  188. }
复制代码


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
How does PHP identify a user's session?How does PHP identify a user's session?May 01, 2025 am 12:23 AM

PHPidentifiesauser'ssessionusingsessioncookiesandsessionIDs.1)Whensession_start()iscalled,PHPgeneratesauniquesessionIDstoredinacookienamedPHPSESSIDontheuser'sbrowser.2)ThisIDallowsPHPtoretrievesessiondatafromtheserver.

What are some best practices for securing PHP sessions?What are some best practices for securing PHP sessions?May 01, 2025 am 12:22 AM

The security of PHP sessions can be achieved through the following measures: 1. Use session_regenerate_id() to regenerate the session ID when the user logs in or is an important operation. 2. Encrypt the transmission session ID through the HTTPS protocol. 3. Use session_save_path() to specify the secure directory to store session data and set permissions correctly.

Where are PHP session files stored by default?Where are PHP session files stored by default?May 01, 2025 am 12:15 AM

PHPsessionfilesarestoredinthedirectoryspecifiedbysession.save_path,typically/tmponUnix-likesystemsorC:\Windows\TemponWindows.Tocustomizethis:1)Usesession_save_path()tosetacustomdirectory,ensuringit'swritable;2)Verifythecustomdirectoryexistsandiswrita

How do you retrieve data from a PHP session?How do you retrieve data from a PHP session?May 01, 2025 am 12:11 AM

ToretrievedatafromaPHPsession,startthesessionwithsession_start()andaccessvariablesinthe$_SESSIONarray.Forexample:1)Startthesession:session_start().2)Retrievedata:$username=$_SESSION['username'];echo"Welcome,".$username;.Sessionsareserver-si

How can you use sessions to implement a shopping cart?How can you use sessions to implement a shopping cart?May 01, 2025 am 12:10 AM

The steps to build an efficient shopping cart system using sessions include: 1) Understand the definition and function of the session. The session is a server-side storage mechanism used to maintain user status across requests; 2) Implement basic session management, such as adding products to the shopping cart; 3) Expand to advanced usage, supporting product quantity management and deletion; 4) Optimize performance and security, by persisting session data and using secure session identifiers.

How do you create and use an interface in PHP?How do you create and use an interface in PHP?Apr 30, 2025 pm 03:40 PM

The article explains how to create, implement, and use interfaces in PHP, focusing on their benefits for code organization and maintainability.

What is the difference between crypt() and password_hash()?What is the difference between crypt() and password_hash()?Apr 30, 2025 pm 03:39 PM

The article discusses the differences between crypt() and password_hash() in PHP for password hashing, focusing on their implementation, security, and suitability for modern web applications.

How can you prevent Cross-Site Scripting (XSS) in PHP?How can you prevent Cross-Site Scripting (XSS) in PHP?Apr 30, 2025 pm 03:38 PM

Article discusses preventing Cross-Site Scripting (XSS) in PHP through input validation, output encoding, and using tools like OWASP ESAPI and HTML Purifier.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.