Search code examples
phpreplacerepeatstr-replaceregexp-replace

How to properly replace strings when you have repeated substrings?


I want to add hyperlinks to urls in a text, but the problem is that I can have different formats and the urls could have some substrings repeated in other strings. Let me explain it better with an example:

Here I have one insidelinkhttp://google.com But I can have more formats like the followings: https://google.com google.com

And right now I have the following links extracted from the above example: ["http://google.com", "https://google.com", "google.com"] and I want to replace those matches with the following array: ['<a href="http://google.com">http://google.com</a>', '<a href="https://google.com">https://google.com</a>', '<a href="google.com">google.com</a>']

If I iterate over the array replacing each element there will be an error as in the above example once that I have properly added the hyperlink for "http://google.com" each substring will be replaced with another hyperlink from "google.com"

Anyone has any idea about how solve that problem?

Thanks


Solution

  • On the basis of your sample string, I have defined 3 different patterns for URL matching and replace it as per your requirement, you can define more patterns in the "$regEX" variable.

    // string
    $str = "Here I have one insidelinkhttp://google.com But I can have more formats like the followings: https://google.com google.com";
    
    /**
     * Replace with the match pattern
     */
    function urls_matches($url1)
    {
      if (isset($url1[0])) {
        return '<a href="' . $url1[0] . '">' . $url1[0] . '</a>';
      }
    }
    
    // regular expression for multiple patterns
    $regEX = "/(http:\/\/[a-zA-Z0-9]+\.+[A-Za-z]{2,6}+)|(https:\/\/[a-zA-Z0-9]+\.+[A-Za-z]{2,6}+)|([a-zA-Z0-9]+\.+[A-Za-z]{2,6}+)/";
    
    // replacing string based on defined patterns
    $replacedString = preg_replace_callback(
      $regEX,
      "urls_matches",
      $str
    );
    
    // print the replaced string
    echo $replacedString;