swap Z for S char between vowels in a string

Asked

Viewed 112 times

2

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

for example

TEREZA , CEZAR, BRAZIL, HOOK

would be

TERESA , CESAR, BRASIL, ANZOL

3 answers

5

Via Lookback

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

Explanation

  • (?<=[a-zA-Z]) - will observe those who come before but not capture.
  • Z - literal character that must 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 to be captured
  • Z - literal character that must be captured
  • ([a-zA-Z]) - group 2 to be captured
  • $1S$2 - replaces what was captured in the 1+S+ group that was captured in Grupo2
  • Perfect, the first regex exchange AZAZA for ASASA, the second line ASAZA. +1

4


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

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

3

Using a vowel list:

$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');

Upshot:

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

BRAZIL

Browser other questions tagged

You are not signed in. Login or sign up in order to post.