preg_replace promblems

Hello,

I am trying to run a piece of code that replaces a set of words with another set of words.

It’s along the lines of 'replace ‘she’ with ‘he’ and replace ‘he’ with ‘she’. But as it runs through each command separately it replaces ‘she’ with ‘he’ then it changes it back again to ‘he’.
Is there any way of it knowing that it shouldn’t change changes again?

Here is code:

<?php $string = file_get_contents('http://www.moregood.co.uk/gender/feeds.php'); $patterns[0] = '/\bher\b/e'; $patterns[1] = '/\bshe\b/e'; $patterns[2] = '/\bhis\b/e'; $patterns[3] = '/\bhim\b/e'; $patterns[4] = '/\bhe\b/e'; $patterns[5] = '/\bmen\b/e'; $patterns[6] = '/\bman\b/e'; $replacement[0] = 'his'; $replacement[1] = 'he'; $replacement[2] = 'her'; $replacement[3] = 'her'; $replacement[4] = 'she'; $replacement[5] = 'women'; $replacement[6] = 'woman'; echo preg_replace( $patterns, $replacement, $string ) ?>

Any help would be greatly appreciated.

Thanks

I would do this replacement in two iterations: first replace ‘she’ to something unique like ~she~ and on second iteration replace ~she~ to he, so that she/he does not interfere on first iteration. This is quick solution, but probably someone here know how to do this better in one iteration, I’d like to learn too :slight_smile:

Sponsor our Newsletter | Privacy Policy | Terms of Service