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
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
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);
preg_replace('~(?<=[a-zA-Z])Z(?=[a-zA-Z])~', 'S', $str);
(?<=[a-zA-Z])
- will observe the ones that come before, but not capture. (?=[a-zA-Z])
- will check what comes next but not capture. preg_replace('~([a-zA-Z])Z([a-zA-Z])~', '$1S$2', $str);
([a-zA-Z])
- group 1 that should be caught ([a-zA-Z])
- group 2 that should be caught $1S$2
- replaces what was captured in group1 + S + that was captured in group2 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