$string = 'Машинист Машиниста Машинисту Машиниста Машинистом Машинисте Машинисты Машинистам Машинистов Машинистам Машинистах'; $patterns = array(); $patterns[0]= '/машинист/'; $patterns[1]= '/Машиниста/'; $patterns[2]= '/Машинисту/'; $patterns[3]= '/Машиниста/'; $patterns[4]= '/Машинистом/'; $patterns[5]= '/Машинисте/'; $patterns[6]= '/Машинисты/'; $patterns[7]= '/Машинистов/'; $patterns[8]= '/Машинистам/'; $patterns[9]= '/Машинистов/'; $patterns[10]= '/Машинистами/'; $patterns[11]= '/Машинистах/'; $replacements = array(); $replacements[0] = 'турист'; $replacements[1] = 'туриста'; $replacements[2] = 'туристу'; $replacements[3] = 'туриста'; $replacements[4] = 'туристом'; $replacements[5] = 'туристе'; $replacements[6] = 'туристы'; $replacements[7] = 'туристов'; $replacements[8] = 'туристами'; $replacements[9] = 'туристов'; $replacements[10] = 'туристами'; $replacements[11] = 'туристах'; echo preg_replace($patterns, $replacements, $string ); 

How can I simplify the regular expression for replacing words with cases?

  • one
    If the words are these, then str_replace ('driver', 'tourist') will give the required effect. You can, of course, also check with regularity for validity of endings. But not all words can be replaced like this because every kind of runaway vowels, etc. in some words they won't let you do it - Mike
  • in this case, only these few words - Radik

2 answers 2

Leaving as is will be the best option. In terms of readability)

By the way, under the key '8', is there an equivalent replacement?

 $patterns[8]= '/Машинистам/'; $replacements[8] = 'туристами'; 

If you have a typo and the endings are the same and the words are only these, you can even without regular ones:

 $string = str_replace('Машинист', 'турист', $string); 

UPD:

You can also replace it, IMHO more readable:

 $replacements = array( 'машинист' => 'турист', 'Машиниста' => 'туриста', 'Машинисту' => 'туристу', 'Машинистом' => 'туристом', ); $string = str_replace(array_keys($replacements), array_values($replacements), $string); 
  • yes it's a typo - Radick

If you need to check the endings, for example, by chance not to change the word 'Typist' then:

 preg_replace('/Машинист(?=(а(ми?|х|)|[уеы]|о[мв]|)\b)/ui','турист',$str); 

And if not, then simple str_replace('Машинист', 'турист', $str); true, unlike preg_replace, it cannot work with different character registers.