Jump to content

Recommended Posts

Ok I'm trying to make word replace but I'm have some problems ,  first I have in my database row "words" have the words it look for to replace row "wordsys" have the replacement word

the problem I'm have is let say the text I want to replace is "My friend is in here house" and row "words" has "My, In , here" in it and the replacement words are in wordsys has "In for My" "We for In" and "gone for here"

 

so first it going to replace "My" with "In" that good ,but then it going back and replacing "In" the we just replaced with "We" and so forth who do I stop it from re-replace a word that it already replace.

<?php

//connect to database

 

$textw = "My friend is in here house";

//load all replacements

$result = mysql_query("SELECT * FROM data");

//replace all words

$words = array();

$replacewords =array();

while ($row = mysql_fetch_assoc($result)) {

    $words[] = $row['words'];

    $replacewords[] = $row['wordsys'];

}

$text = str_replace($words,$replacewords,$textw);

echo $text;

?>

 

 

Thank you for your help

Link to comment
https://forums.phpfreaks.com/topic/246197-help-stop-re-replaceing-a-word/
Share on other sites

One possible way -

<?php
//connect to database

$textw = "My friend is in here house";

// determine which words to retrieve (save some processing and query time)
$parts = explode(' ',$textw); // $parts is also used later in the replace operation
$find = implode("','",$parts);

//load just the replacements
$query = "SELECT * FROM data WHERE words IN ('$find')";
$result = mysql_query($query);

//get replacement words
$replacewords =array();
while ($row = mysql_fetch_assoc($result)) {
    $replacewords[strtolower($row['words'])] = $row['wordsys']; // key is the original word, value is the replacement
}
foreach($parts as $key=>$part){
if(isset($replacewords[strtolower($part)])){
	$parts[$key] = $replacewords[strtolower($part)];
}
}
$text = implode(' ',$parts);
echo $text;
?>

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.