Jump to content

str_replace() en-mass


gerkintrigg

Recommended Posts

Is there a way of using a database to check for links so they can automatically replace a word with a link to that word? Is there a way to do this with loads of words? I want to use a fairly substantial database to check web content against and alter the words output before the system outputs them.

 

Any suggestions?

Link to comment
Share on other sites

All you really need is a map of words to urls.  You can store that internally in PHP as an associative array or an array of objects.  If you go that route then you'll have to manually edit PHP code to change associations.

 

You could just as easily store this list in a database in a two-column table.

 

As far as doing the find-and-replace algorithm, I don't think str_replace() will be suitable for your needs.  Just examine the following code and its output:

<?php
$str = 'My dog is so nice.' . "\n";
echo $str;
$str0 = str_replace( array( 'dog', 'nice' ), array( 'cat', 'mean' ), $str );
echo $str0;
$str1 = str_replace( array( 'cat', 'dog' ), array( 'bird', 'cat' ), $str );
echo $str1;
$str2 = str_replace( array( 'dog', 'cat' ), array( 'cat', 'bird' ), $str );
echo $str2;
?>

My dog is so nice.
My cat is so mean.
My cat is so nice.
My bird is so nice.

 

As you can see, the order in which you declare the search and replacement terms is important.

 

You'd probably want to write your own algorithm for parsing each word of the text you want to search over.  strtok() may come in handy for this.

 

Lastly, depending on the content-size of the document you're searching and the size of the replacement list, this could be an expensive operation in terms of computing resources required.  As such, you may want to consider implementing some sort of caching feature.

Link to comment
Share on other sites

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.