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

Recommended Answers

All 5 Replies

You can use:

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

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...

$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 -

$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 -.

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.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.