Reputation:
I have a database of strings and a database of words and their corrections. I need to find the words within the strings and replace them with their corrections. I cannot figure out how to do it and have it loop through all of the strings in the database. I need help.
I was thinking along the lines of the following pseudo code"
//while loop to grab all the strings from db
//add all the words to look for to an array
//add all of the word replacements to an array
//preg replace or str replace the words with the replacements in the string.
Any ideas?
Upvotes: 0
Views: 675
Reputation: 10771
I would take a look at using strtr
. This takes a string (sentence) as the first parameter and an array of key/value pairs as replacement text.
<?php
$sentence = "The quick brown fox jumps over the lazy dog";
$replacements = array("quick" => "fast", "brown" => "white", "fox" => "hair");
echo strtr($sentence, $replacements);
Yields:
The fast white hair jumps over the lazy dog
I would also read up on Tokenization
if you are not familiar with it as a concept. It may help you understand the underlying logic behind how this works.
Upvotes: 1
Reputation: 12613
If you put all of the strings into an array $orig
, all of the words into an array $words
, and all of the corrections in to an array $corrections
, you can just do this:
$corrected = str_replace($words, $corrections, $orig);
Here is the documentation on str_replace
.
Upvotes: 0