PHP如果字符重复多次[关闭]

问题描述:

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.

我有一个函数可以将随机点添加到字符串并将更改的字符串存储在变量中,但是,有时它 连续添加多个点。 例如: p>

  te ... stin.g 
  code>  pre> 
 
 

或 p> t..e.st.in.g 代码> PRE>

和 p>

  TE。  st.in .... g 
  code>  pre> 
 
 

......等等。 p>

我在想,我怎么能 检测一行中是否有多个点,并将它们合二为一。 例如,上面的第一个字符串将成为: p>

  te.stin.g 
  code>  pre> 
 
 

第二个字符串.. 。 p>

  test.in.g 
  code>  pre> 
 
 

第三个...... p> \ n

  te.st.in.g 
  code>  pre> 
 
 

...等等。 p>

如何 我可以用PHP来表达这一点吗? 我不知道从哪里开始。 p> div>

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.

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);