I have a number of sentences where I want to replace each one with a single word, this word (or a variant of it) is contained in the sentence. I put my regex patterns in an indexed array which are single words to find in each string. I have a second array which have the replacement words (These words are just simple examples):
$pattern = array('/one/','/two/','/three/');
$replacements = array('ones','twos','threes');
Say for example I have the sentence:
"There is one tree"
Then I want to replace the sentence with
"ones"
I have tried both preg_replace
and preg_replace_calback
and are not sure which one to use or whether I should use preg_match
I am trying this:
$simplified = preg_replace_callback($pattern, function($matches) {
return $replacements[array_search($matches[0], $pattern, true)];
}, $simplified, 1);
where $simplified
contains the word which I want to replace the sentence with.
I believe that array_search is applicable for associated arrays but I tried looping through the indexed array as well. I have to find the regex that actually matched the word in the sentence and need to get the index of that match to find the correct word in the replacement array. This is long winded and could be the wrong approach.
My questions are: 1. Am I approaching this wrong? 2. If this approach can work, how do I get the sentence replaced with a single word?