Replace URLs in text with HTML links

后端 未结 17 1986
栀梦
栀梦 2020-11-22 11:27

Here is a design though: For example is I put a link such as

http://example.com

in textarea. How do I get PHP t

17条回答
  •  轮回少年
    2020-11-22 12:05

    As I mentioned in one of the comments above my VPS, which is running php 7, started emitting warnings Warning: preg_replace(): The /e modifier is no longer supported, use preg_replace_callback instead. The buffer after the replacement was empty/false.

    I have rewritten the code and made some improvements. If you think that you should be in the author section feel free to edit the comment above the function make_links_blank name. I am intentionally not using the closing php ?> to avoid inserting whitespace in the output.

    ]*>.+?<\/a>)
                     (?:]*>.+<\/a>)
                     |
                     ([^="\']?)((?:https?|ftp):\/\/[^<> \n\r]+)
                 )#six' => function ( $matches ) {
                    $r1 = empty( $matches[1] ) ? '' : $matches[1];
                    $r2 = empty( $matches[2] ) ? '' : $matches[2];
                    $r3 = empty( $matches[3] ) ? '' : $matches[3];
    
                    $r2 = empty( $r2 ) ? '' : App_Updater_String_Util::set_protocol( $r2 );
                    $res = ! empty( $r2 ) ? "$r1$r2$r3" : $matches[0];
                    $res = stripslashes( $res );
    
                    return $res;
                 },
    
                '#(^|\s)((?:https?://|www\.|https?://www\.)[^<>\ \n\r]+)#six' => function ( $matches ) {
                    $r1 = empty( $matches[1] ) ? '' : $matches[1];
                    $r2 = empty( $matches[2] ) ? '' : $matches[2];
                    $r3 = empty( $matches[3] ) ? '' : $matches[3];
    
                    $r2 = ! empty( $r2 ) ? App_Updater_String_Util::set_protocol( $r2 ) : '';
                    $res = ! empty( $r2 ) ? "$r1$r2$r3" : $matches[0];
                    $res = stripslashes( $res );
    
                    return $res;
                },
    
                // Remove any target attribs (if any)
                '#]*)target="?[^"\']+"?#si' => ']+)>#si' => '',
    
                // Make emails clickable Mailto links
                '/(([\w\-]+)(\\.[\w\-]+)*@([\w\-]+)
                    (\\.[\w\-]+)*)/six' => function ( $matches ) {
    
                    $r = $matches[0];
                    $res = ! empty( $r ) ? "$r" : $r;
                    $res = stripslashes( $res );
    
                    return $res;
                },
            ];
    
            foreach ( $patterns as $regex => $callback_or_replace ) {
                if ( is_callable( $callback_or_replace ) ) {
                    $text = preg_replace_callback( $regex, $callback_or_replace, $text );
                } else {
                    $text = preg_replace( $regex, $callback_or_replace, $text );
                }
            }
    
            return $text;
        }
    }
    

提交回复
热议问题