gerkintrigg Posted June 11, 2012 Share Posted June 11, 2012 Hello. A few years ago, I spent ages working on a way to replace multiple substrings within a large body of text. I can't remember what I did, where I stored the code or how to do it, so I was hoping you could help. I want to take a large body of text and replace keywords from within the text with links to a page about that topic in a similar way to wikipedia. Is there an easy way of doing this without manually adding the links? Bear in mind that the database will grow quite a lot and so str_replace is probably going to be innadequate. Thanks. Neil Quote Link to comment https://forums.phpfreaks.com/topic/263988-replacing-lots-of-strings/ Share on other sites More sharing options...
PFMaBiSmAd Posted June 11, 2012 Share Posted June 11, 2012 To perform the actual replacement in the string, see the following example (you would replace the <span></span> tag with a <a href='...'></a> tag) - <?php $search = "php|web"; // can be a single word or an OR'ed '|' list of words $string = "PHP is the web scripting language of choice, php, Web, phpweb"; $string = preg_replace("/\b($search)\b/i",'<span class="highlight">\1</span>',$string); // replace whole words only echo $string; To produce the list of words in the $search variable in that code, you would break up the initial string of text into words in an array, use array_unique to remove duplicates, perhaps filter the array to remove common words that would never end up being links, then query the database to find a list of the the words in the array that are to be links (implode the array of keywords and use it in an IN() comparison in the query statement.) You would then build the $search variable in that code from the matching words that the database query returned. Quote Link to comment https://forums.phpfreaks.com/topic/263988-replacing-lots-of-strings/#findComment-1352910 Share on other sites More sharing options...
gerkintrigg Posted June 11, 2012 Author Share Posted June 11, 2012 perfect, that'll do it. thanks! Quote Link to comment https://forums.phpfreaks.com/topic/263988-replacing-lots-of-strings/#findComment-1352927 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.