简体   繁体   中英

PHP str_ireplace on Mysql Result

I need to get a value from a MySQL table and then replace it with something else.

I have a Find and Replace table which has three columns: ID, Find, Replace. I want to loop through each row of that table and then search for the find value in another table and change it to the replace.

For Example:

ID | Find                   | Replace
1  | This is a product name | Product Name 

I have created a loop to go through each row, and then inside of that another to loop through the table I am replacing values in:

$lookups = mysqli_query($connect, "SELECT * FROM value_lookup");

while($row = mysqli_fetch_assoc($lookups)) {
    $find = $row['Find'];
    $replace = $row['Replace'];

    $table = mysqli_query($connect, "SELECT ID, Reference FROM table");

    while($row = mysqli_fetch_assoc($table)) {
        $ref = $row['Reference'];
        $newRef = str_ireplace($find, $replace, $ref);

        echo $newRef . PHP_EOL;
        mysqli_query($connect, "UPDATE table SET Reference = '$newRef' WHERE Reference LIKE '%$find%'");
    }
}

It seems to me that the str_ireplace isn't working because the values I'm using are an associative array. If I manually type the values as a string it works fine.

I need to know how to get the values as a string, or convert them to one. I do have to use str_ireplace as well, I cant just straight take the find value and change to the replace. As some values have different prefixes and suffixes which I want to keep the same:

These are some towels: Red TO Towels: Red
These are some towels: Blue TO Towels: Blue

While making a SQLfiddle for mickmackusa I have actually managed to work this out for myself using pure SQL.

DELIMITER //
CREATE PROCEDURE findreplace()
BEGIN   
DECLARE cnt INT DEFAULT 0;
DECLARE total INT DEFAULT 0;
DECLARE original VARCHAR(255);
DECLARE new VARCHAR(255);

SELECT COUNT(*) FROM lookup INTO total;

WHILE cnt < total DO
    SELECT find FROM lookup LIMIT cnt, 1 INTO original;
    SELECT repl FROM lookup LIMIT cnt, 1 INTO new;

    UPDATE test SET Reference = replace(Reference, original, new);
    SET cnt = cnt + 1;
END WHILE;
END//

You can do this by using a single update query. You can use REGEXP OR LIKE operator in WHERE clause for respective find & replace's, below are the queries:

Using REGEXP :

UPDATE table, findreplacetable SET table.name = REPLACE(table.name, findreplacetable.find_, findreplacetable.replace_) WHERE table.name REGEXP CONCAT('[[:<:]]', findreplacetable.find_,'[[:>:]]');

Using LIKE :

UPDATE table, findreplacetable SET table.name = REPLACE(table.name, findreplacetable.find_, findreplacetable.replace_) WHERE table.name LIKE CONCAT('%', findreplacetable.find_,'%');

Hope it'll help you out.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM