Usage of the PHP function preg_match_all ()

Source: Internet
Author: User

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

 
  1. <? Php
  2. // Function: Convert the link address in the text into HTML
  3. // Input: String
  4. // Output: String
  5. Function url2html ($ text)
  6. {
  7. // Match a URL until Blank
  8. Preg_match_all ("/http ://? [^ S] +/I"
    , $ Text, $ links );
  9. // Set the length of the URL displayed on the page
  10. $ Max_size = 40;
  11. Foreach ($ links [0] as $ link_url)
  12. {
  13. // Calculate the URL length. If the value of $ max_size is exceeded, it is shortened.
  14. $ Len = strlen ($ link_url );
  15. If ($ len> $ max_size)
  16. {
  17. $ Link_text = substr ($ link_url, 0, $ max_size )."...";
  18. } Else {
  19. $ Link_text = $ link_url;
  20. }
  21. // Generate HTML text
  22. $ Text = str_replace ($ link_url ,"
    <A href = '$ link_url'> $ link_text ", $ text );
  23. }
  24. Return $ text;
  25. }
  26. // Run the instance
  27. $ Str = "this is a multi-line text that contains multiple URL URLs.
    Welcome to http://www.taoboor.com ";
  28. Print url2html ($ str );
  29. /* Output result
  30. This is a multi-line text that contains multiple URL links
    . Welcome to <a href = 'HTTP: // www.taoboor.com '>
  31. Http://www.taoboor.com
  32. */
  33. ?>

We hope that you can fully master the application of the above PHP function preg_match_all.


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.