M
M
Max2019-03-17 20:02:39
PHP
Max, 2019-03-17 20:02:39

How to come up with an algorithm - to replace words in HTML with synonyms from an array at each occurrence?

I can not figure out how to make a replacement in the HTML code of the page.
There is an array with words (there will be about 1k arrays, each with 3-50 elements)
['rain ', 'rainfall', 'storm']
It is necessary that the occurrence of each of these words in the text be replaced by any other from the array, in the text any of the words in the array can occur 0-N times. At the same time, not all N occurrences of the word rain should be replaced by storm, but in random order with rainfall, and other options (if any).
Option 1:

str_replace ( mixed $search , mixed $replace , mixed $subject [, int &$count ] ) : mixed

$search = Submit an array with synonyms
$replace = Submit some construction that is then processed by a separate function, for example, a construction of the form "spintax" {rain|clown|snow}.
Option 2:
Create a certain index / multidimensional array of each word available, for example, I have 50 arrays with substitution options, a certain word was found from array 20 with index 2 , replace it with $WORD_20_2 in the text, then search with a separate function for $word_20_2 regular expression and change to elements array 20 and a word with NOT index 2.
Both solutions seem to me not elegant enough, there are probably more interesting and simpler options. I also thought to do it through preg_match_all with an index on offset, but it doesn’t work because the length of the words is always different.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
Dimonchik, 2019-03-17
@dimonchik2013

you think google naeepat? he spun such smart ones on the patent
on the subject: with
the first pass you change what you are looking for for SERVICE
, the second you form an array of replacements (clean in a simple way, but you can also use it for an adult, with cases) with the
third you change SERVICE for array elements

R
Robur, 2019-03-17
@Robur

break everything into an array of words - and run through it with a loop or map collecting it back, replacing the words as you like along the way

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question