InThe following is an example of converting the URL link address in the text into HTML code. Code 6.4 is an example of using the PHP function preg_match_all.
Code 6.4 converts the link address in the text into HTML
- <? Php
- // Function: Convert the link address in the text into HTML
- // Input: String
- // Output: String
- Function url2html ($ text)
- {
- // Match a URL until Blank
- Preg_match_all ("/http ://? [^ S] +/I"
, $ Text, $ links );
- // Set the length of the URL displayed on the page
- $ Max_size = 40;
- Foreach ($ links [0] as $ link_url)
- {
- // Calculate the URL length. If the value of $ max_size is exceeded, it is shortened.
- $ Len = strlen ($ link_url );
- If ($ len> $ max_size)
- {
- $ Link_text = substr ($ link_url, 0, $ max_size )."...";
- } Else {
- $ Link_text = $ link_url;
- }
- // Generate HTML text
- $ Text = str_replace ($ link_url ,"
<A href = '$ link_url'> $ link_text ", $ text );
- }
- Return $ text;
- }
- // Run the instance
- $ Str = "this is a multi-line text that contains multiple URL URLs.
Welcome to http://www.taoboor.com ";
- Print url2html ($ str );
- /* Output result
- This is a multi-line text that contains multiple URL links
. Welcome to <a href = 'HTTP: // www.taoboor.com '>
- Http://www.taoboor.com
- */
- ?>
We hope that you can fully master the application of the above PHP function preg_match_all.