Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 3 of 3
  1. #1
    Senior Coder
    Join Date
    Jul 2005
    Location
    UK
    Posts
    1,051
    Thanks
    6
    Thanked 13 Times in 13 Posts

    Find/Replace only *one* instance

    I have written a script that scans each new entry in my database for keywords and phrases that exist elsewhere on my site, in order that hyperlinks are automatically created to relevant content. It's very straight forward, simply looping through existing database entries looking for matches in the text, and using str_replace to insert the links where a match is found.

    I'm at an impasse though because sometimes I end up with many of the same link appearing in each entry - I'd want to limit it to a maximum of one of each link (as well as limiting it to a maximum number of links overall - although that part is easy).

    I'd thought of adding each keyword or phrase to an array to check against before inserting a link, but I don't think this will work since str_replace does all replacements at once. I then thought of splitting the text into an array and looping through it replacing one word at a time, but that won't work because many of the keywords are two or more words. So in short, I'm stumped. Any ideas?

    (I know the Alinks extension for Wordpress can do this, but I've not had much luck reverse engineering it because it's a rather complicated collection of scripts for me).

  • #2
    Senior Coder NancyJ's Avatar
    Join Date
    Feb 2005
    Location
    Bradford, UK
    Posts
    3,169
    Thanks
    19
    Thanked 65 Times in 64 Posts
    If you use preg_replace you can pass a limit parameter to specify the maximum number of matches to replace. I've never actually tried it but it should work for you.
    http://www.php.net/manual/en/function.preg-replace.php

  • #3
    Senior Coder
    Join Date
    Jul 2005
    Location
    UK
    Posts
    1,051
    Thanks
    6
    Thanked 13 Times in 13 Posts
    Oh nice, thanks Nancy. Nice and simple


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •