0

Hi,

I need to replace "-" from a string . Ie

Just need a "-" between two words. ie

standard format is : Hello-world-php

If I got a string like this 'Hello--world----php'

I just need to rewrite that in to 'Hello-world-php' format .

Hope you understand this ..

Please help
Thanks
Rajeesh

5
Contributors
5
Replies
11
Views
6 Years
Discussion Span
Last Post by chrishea
0

chrishea is telling nice solution...but you have to just manage and search in your string that how many consecutive '-' are present....and then use the method told by him...Hope it's clear...

0
$result = str_replace ("--","-",$string);

Should remove all
if there's 3 in a row: ---
It would find the first two - and replace with one: [-]-
leaving -- which is then replaced by -

Edited by makman99: n/a

0
$result = str_replace ("--","-",$string);

Should remove all
if there's 3 in a row: ---
It would find the first two - and replace with one: [-]-
leaving -- which is then replaced by -

Neither has the desired behaviour.
str_replace doesn't rescan already replaced input and so --- will be matched as -, replaced by [-]-. It will not reinterpret the already replaced [-]- as .


Try this instead

preg_replace("/[-]+/", "-", $in);

This will perform greedy matches by default, matching as many consecutive -'s as it can find and replacing the whole with only one -.

0

Sorry, I blew that one. You could only do the str_replace if you used a while loop since it doesn't rescan. The preg_replace is definitely simpler.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.