简体   繁体   English

用多个字符串替换某些单词PHP

[英]Replace certain words in multiple strings PHP

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? 有任何想法吗?

I would take a look at using strtr . 我将看看使用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. 如果您不熟悉Tokenization作为一个概念,我也将继续阅读。 It may help you understand the underlying logic behind how this works. 它可以帮助您了解其工作原理的基本逻辑。

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: 如果将所有字符串放入$orig数组中,将所有单词放入$words数组中,并将所有更正放入数组$corrections ,则可以执行以下操作:

$corrected = str_replace($words, $corrections, $orig);

Here is the documentation on str_replace . str_replace上的文档。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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