2

Im trying to right a script that divides vowels and suffixes with a hyphen.

<?php
$string = 'celebrationing';
$patterns = array();
$patterns[0] = '/a/';
$patterns[1] = '/e/';
$patterns[2] = '/i/';
$patterns[3] = '/o/';
$patterns[4] = '/u/';
$patterns[5] = '/tion/';

$replacements = array();
$replacements[0] = '-a';
$replacements[1] = '-e';
$replacements[2] = '-i';
$replacements[3] = '-o';
$replacements[4] = '-u';
$replacements[5] = '-tion';

echo preg_replace($patterns, $replacements, $string);


?>

The script works fine for vowels, but when i comes to the suffix -tion, it isnt printing the hyphen.

Output: c-el-ebr-at-i-on-ing

What im thinking is the fact that both -i and -o are vowels is whats messing the whole process up.

How do I allow all six patterns to be recognized, with all instances of -tion superceding -i and -o?

0

2 Answers 2

6

You can use a simpler regex:

preg_replace('/tion|[aeiou]/', "-$0", $string);

regex101 demo

The regex first tries to match tion which thus prevents the matching of i and o later on in the same match.

Sign up to request clarification or add additional context in comments.

1 Comment

This is better than what I was thinking! Thanks Jerry!!
2

Not as elegant as Jerry's solution, this one uses negative-lookahead & lookbehind:

<?php

$string = 'celebrationing';
$patterns = array();
$patterns[0] = '/a/';
$patterns[1] = '/e/';
$patterns[2] = '/i(?!on)/';
$patterns[3] = '/o(?<!ti)(?!n)/';
$patterns[4] = '/u/';
$patterns[5] = '/tion/';

$replacements = array();
$replacements[0] = '-a';
$replacements[1] = '-e';
$replacements[2] = '-i';
$replacements[3] = '-o';
$replacements[4] = '-u';
$replacements[5] = '-tion';

echo preg_replace($patterns, $replacements, $string);

OUPUT:

c-el-ebr-a-tion-ing

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.