user2333968
user2333968

Reputation: 135

PHP - str_replace multiple symbols

I have the following string "Il-kelb ta Mariia jismu il-Bobo"

Users usually enter the sentence above. Sometimes they enter the sentence as

"Il-kelb ta Mariia jismu il--Bobo" - i.e. double dashes OR
"Il---kelb ta Mariia jismu il---Bobo" - i.e. double dashes; or 
"Il-----------------------kelb ta Mariia jismu il-------Bobo" - i.e. double dashes; or 

I usually use str_replace e.g. str_replace('--','-') If its three dashes its str_replace('---','-') If its four dashes its str_replace('----','-')

In certain instances it will echo -- or --- regardless

I would like to know how to make a function not to allow two dashes next to each other, otherwise the str_replace('----','-') will go for unlimited combinations.

I would like to output one dash if they are next to each other.

Upvotes: 0

Views: 251

Answers (2)

idmean
idmean

Reputation: 14875

Use preg_replace

preg_replace("/-{2,}/", "-", $string);

Upvotes: 4

Praveen Kumar Purushothaman
Praveen Kumar Purushothaman

Reputation: 167192

You can do it using a simple while loop this way:

while (strpos($string, "--") !== false)
  $string = str_replace("--", "-", $string);

Or if you are planning to use regular expressions, you can do this way:

$string = preg_replace("/\-+/", "-", $string);

Upvotes: 1

Related Questions