What I got:
array(4) {
[0]=>
string(7) "text???"
[1]=>
string(7) "???text"
[2]=>
string(11) "text???text"
[3]=>
string(24) "text ? ? ? ? ? text"
}
What I want:
array(4) {
[0]=>
string(5) "text?"
[1]=>
string(6) "? text"
[2]=>
string(10) "text? text"
[3]=>
string(10) "text? text"
}
My approach:
<?php
$array = array (
"text???",
"???text",
"text???text",
"text ? ? ? ? ? text"
);
foreach ($array as &$string) {
$string = preg_replace('!(\s|\?|\!|\.|:|,|;)+!', '$1 ', $string);
}
var_dump($array);
Result:
array(4) {
[0]=>
string(6) "text? "
[1]=>
string(6) "? text"
[2]=>
string(10) "text? text"
[3]=>
&string(9) "text text"
}
Conclusion: My approach has two flaws I'm aware of. Firstly, it adds a whitespace behind every replacement even when it's the end of the string. I assume I could use trim
after preg_replace
, but I'd rather have it removed by regular expression if possible so I don't need to. Secondly it breaks on strings like the last one of the example above for some reason.