exchange char Z for S between vowels in a string

2

How can I change all occurrences of the letter Z between S within a string

for example

  

TEREZA, CEZAR, BRAZIL, ANZOL

would be

  

TERESA, CESAR, BRAZIL, ANZOL

    
asked by anonymous 11.08.2016 / 17:09

3 answers

4

You can use two groups to check the existence of the vowels between Z , after they are captured, just play $1 (first group), $2 (second group) between S

$str = 'TEREZA , CEZAR, BRAZIL, ANZOL';
echo preg_replace('/(A|I|O|U|E)Z(A|I|O|U|E)/', '$1S$2', $str);
    
11.08.2016 / 17:13
5

Via lookback

preg_replace('~(?<=[a-zA-Z])Z(?=[a-zA-Z])~', 'S', $str);

Explanation

  • (?<=[a-zA-Z]) - will observe the ones that come before, but not capture.
  • Z - literal character to be captured.
  • (?=[a-zA-Z]) - will check what comes next but not capture.

Via group

preg_replace('~([a-zA-Z])Z([a-zA-Z])~', '$1S$2', $str);

Explanation

  • ([a-zA-Z]) - group 1 that should be caught
  • Z - literal character to be captured
  • ([a-zA-Z]) - group 2 that should be caught
  • $1S$2 - replaces what was captured in group1 + S + that was captured in group2
11.08.2016 / 17:13
3

Using list of vowels:

$input = ['TEREZA' , 'CEZAR', 'BRAZIL', 'ANZOL'];
print_r(preg_replace('/([aeiou]+)z([aeiou]+)/i', '$1S$2', $input));

or:

echo preg_replace('/([aeiou]+)z([aeiou]+)/i', '$1S$2', 'BRAZIL');

Result:

  

Array ([0] => TERESA [1] => CESAR [2] => BRAZIL [3] => ANZOL)

     

BRAZIL

    
11.08.2016 / 17:15