NovumCoder
NovumCoder

Reputation: 4637

PHPs preg_replace replaces only once in a string

Why does preg_replace replace my searched string only once in a string?

I have a string "Hello------World".

I use this

preg_replace( '#--#', '-', 'Hello------World');

But preg_replace returns "Hello---World". So it replaces the first occurence and continues not checking if there still is any occurence of -- How to get "Hello------World" to "Hello-World" ?

Upvotes: 1

Views: 1034

Answers (2)

Joost
Joost

Reputation: 10413

What you're seeing is correct behavior. The regexp matches two dashes, replaces them with one, then searches on. Finds two dashes again, replaces them with one. So six dashes will become three dashes.

The solution would be to match multiple dashes, then replace with one dash:

preg_replace( '#--+#', '-', 'Hello------World');

The + in the regexp will match at least one dash, but matches as much of those characters as possible. More specifically, it matches all dashes until a non-dash occurs in the string. Thus it will now find all six dashes, replace them with one dash, and searches on to find more dashes.

Upvotes: 3

andersandersson666
andersandersson666

Reputation: 95

I think you need to add a global flag to the regexp, or else it just matches the first occurance of the string. like preg_replace( '#--#/g', '-', 'Hello------World'); or something

Upvotes: -2

Related Questions