Regular expression replace a word by a link

后端 未结 7 2426
走了就别回头了
走了就别回头了 2020-12-18 11:51

I want to write a regular expression that will replace the word Paris by a link, for only the word is not ready a part of a link.

Example:

    i\'m l         


        
7条回答
  •  盖世英雄少女心
    2020-12-18 12:08

      $pattern = 'Paris';
      $text = 'i\'m living in Paris,  near Paris Gare du Nord,  i love Paris.';
    
      // 1. Define 2 arrays:
      //  $matches[1] - array of links with our keyword
      //  $matches[2] - array of keyword
      preg_match_all('@(]*?>[^<]*?'.$pattern.'[^<]*?)|(?
      $number = array_search($pattern, $matches[2]);
    
      // Keyword exists, let's go rock
      if ($number !== FALSE) {
    
        // Replace all link with temporary value
        foreach ($matches[1] as $k => $tag) {
          $text = preg_replace('@(]*?>[^<]*?'.$pattern.'[^<]*?)@', 'KEYWORD_IS_ALREADY_LINK_'.$k, $text, 1);
        }
    
        // Replace our keywords with link
        $text = preg_replace('/(?'.$pattern.'', $text);
    
        // Return link
        foreach ($matches[1] as $k => $tag) {
    
          $text = str_replace('KEYWORD_IS_ALREADY_LINK_'.$k, $tag, $text);
        }
    
        // It's work!
        echo $text;
      }
    

提交回复
热议问题