Use a regular expression:
$string = preg_replace('/\.{2,}/', '.', $string);
{2,}
means 2 or more of the preceding expression, which is a literal .
.
Go to regular-expressions.info to learn all about regular expressions.
Question
I have a function that adds random dots to a string and stores the altered string in a variable, however, sometimes it adds multiple dots in a row. For example:
te...stin.g
or
t..e.st.in.g
or
te.st.in....g
...and so on.
I was wondering, how can I detect if there are multiple dots in a row, and just make them into one. So for example the first string above would become:
te.stin.g
the second...
t.e.st.in.g
the third...
te.st.in.g
...and so on.
How can I accmplish this with PHP? I have no idea where to start.
Solution
Use a regular expression:
$string = preg_replace('/\.{2,}/', '.', $string);
{2,}
means 2 or more of the preceding expression, which is a literal .
.
Go to regular-expressions.info to learn all about regular expressions.
OTHER TIPS
You may edit your function so that it no more adds multiple dots in a row. Anyway, if that isn’t the expected behaviour of your function, apply preg_replace
to its output in order to get rid of those multiple dots. Let’s say $str
is the output of your function. Then:
$str = preg_replace("/\\.{2,}/", ".", $str);