Jump to content

Recommended Posts

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

Link to comment
https://forums.phpfreaks.com/topic/263988-replacing-lots-of-strings/
Share on other sites

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.

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.