-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathremove_or_add.php
More file actions
33 lines (30 loc) · 1.23 KB
/
remove_or_add.php
File metadata and controls
33 lines (30 loc) · 1.23 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
<?php
// 7 kyu - Exclamation marks series #9: Remove or add a exclamation mark at the end of words of the sentence
// Remove or add a exclamation mark at the end of words of the sentence. Words are separated by spaces in the sentence. That is: If a word has one ! at the end, remove it; If a word has no ! at the end, add a ! to the end; If there are more than one ! at the end of word, keep it.
//
// Examples
// removeOrAdd("Hi!") === "Hi"
// removeOrAdd("Hi! Hi!") === "Hi Hi"
// removeOrAdd("Hi! Hi") === "Hi Hi!"
// removeOrAdd("Hi! Hi Hi!!") === "Hi Hi! Hi!!"
// removeOrAdd("!Hi! !Hi !Hi!!") === "!Hi !Hi! !Hi!!"
function remove_or_add(string $s): string {
return implode(' ', array_map(function ($w) {
if ($w[strlen($w) - 1] !== '!') {
return $w . '!';
} else if ( $w[strlen($w) - 1] === '!' && $w[strlen($w) - 2] !== '!') {
return substr($w, 0, -1);
} else {
return $w;
}
},explode(' ', $s)));
}
// Alternative Solution:
// function remove_or_add(string $s): string {
// return implode(' ', array_map(function ($w) {
// if (preg_match('/[^\!]$/', $w)) return $w . '!';
// if (preg_match('/\!{2,}$/', $w)) return $w;
// return preg_replace('/\!$/', '', $w);
// },explode(' ', $s)));
// }
?>