convert url to links from string except if they are in an attribute of an html tag

后端 未结 4 1959
我在风中等你
我在风中等你 2020-12-16 01:21

I am trying to convert, from a textarea input ($_POST[\'content\']), all urls to link.

$content = preg_replace(\'!(\\s|^)((https?://)+[a-z0-9_./         


        
4条回答
  •  醉梦人生
    2020-12-16 02:12

    Let me suggest something less straight forward: split the input text into the html and non-html parts, then process the non-html parts with your regexp combining the text back into one piece. Smth. like:

      )/Ums', $_POST['content'], -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);
      $result = '';
      foreach ($chunks as $chunk) {
        if (substr($chunk,0,1) != '<') {
          /* do your processing on $chunk */
        }
        $result .= $chunk;
      }
    

    Some additional advices:

    1. try to save the source text and do the transformation when displaying it. This will allow you to improve/fix your rendering code if in future you find a new problem/idea.
    2. (https?://)+ shouldn't be in brackets and you don't need +, cause it matches "https://https://some.com" - just put https?://[a-z0-9_./?=&-]+
    3. the same about (www.)+ :)

提交回复
热议问题