function Sharing for PHP content keyword substitution

Source: Internet
Author: User
  1. /**

  2. * Content Keyword Replacement
  3. * by bbs.it-home.org
  4. */

  5. $arr =array (

  6. "Shoes" = "shoes",
  7. "Socks" = "socks",
  8. "Skirt" = "skirt",
  9. "Dresses" and "dresses",
  10. );
  11. $str = "Shoes socks shoes sock shoe socks shoes socks shoes socks skirt dress";
  12. $str =replacelink ($str, $arr, 3);
  13. Echo $str;

  14. Public Function Replacelink ($STR, $arr, $maxcount =3000) {

  15. Match a picture
  16. Preg_match_all ("/(]*>)/ius", $str, $imgs);
  17. Preg_match_all ("/(.*<\/a>)/ius", $str, $links);
  18. Replace pictures and links
  19. if ($links [1]) {
  20. foreach ($links [1] as $k = + $v) {
  21. $str =str_replace ($v, "@links_ $k", $str);
  22. }
  23. }
  24. if ($imgs [1]) {
  25. foreach ($imgs [1] as $k = + $v) {
  26. $str =str_replace ($v, "@imgs_ $k", $str);
  27. }
  28. }
  29. Match end
  30. $str =strtr ($str, $arr);
  31. Preg_match_all ("/(.*<\/a>)/ius", $str, $a);
  32. $a = $a [1];
  33. $c =array_count_values ($a);
  34. if ($c) {
  35. $KK = 0;
  36. foreach ($c as $k = = $v) {
  37. if ($v) {
  38. if ($kk < $maxcount) {
  39. $v = $v-1;
  40. }
  41. $str =preg_replace ("/". $this->replace_quote ($k). " /i ", Str_replace (" # "," "", Strip_tags ($k)), $str, $v);
  42. }
  43. $kk + +;
  44. }
  45. }
  46. Restore pictures and Links
  47. if ($links [1]) {
  48. foreach ($links [1] as $k = + $v) {
  49. $str =str_replace ("@links_ $k", $v, $STR);
  50. }
  51. }
  52. if ($imgs [1]) {
  53. foreach ($imgs [1] as $k = + $v) {
  54. $str =str_replace ("@imgs_ $k", $v, $STR);
  55. }
  56. }
  57. return $str;
  58. }

  59. function Replace_quote ($STR) {

  60. $str =preg_quote ($STR);
  61. $str =str_replace ("/", "\ \", $STR);
  62. return $str;
  63. }

Copy Code
  • 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.