newbtophp
newbtophp

Reputation: 175

Replacing all proceeding underscores with 1 underscore using a regex?

I need some help, I have a string which looks like below:

$p__________________________________________________________________________________________________________________________________________, &$s___________________________________________________________________________________________________________________________________________, &$k____________________________________________________________________________________________________________________________________________, &$nft_____________________________________________________________________________________________________________________________________________)

and was wondering if I could use a regex to turn it into:

$p_, &$s_, &$k_, &$nft_)

Which is basically removing all the (so theirs no specific amount but theirs atleast 1) proceeding underscores, and replace them with 1 underscore.

I've tried the following pattern but no luck:

preg_replace('#(\$[a-z]{1,3})[_]+#', '$1', $string);

PS: The reason a preg_replace (regex) is preffered (although I understand its not 100% always correct) because it's more precise then using a regular string replacing function.

Thanks and appreciate all help.

Upvotes: 0

Views: 1548

Answers (3)

user557597
user557597

Reputation:

You are on the right track, just forgot a _ after the variable.

If you need an anchor -

\$letters anchor: #(\$[a-z]{1,3}_)_+# with $1

Letter anchor: #([a-z]_)_+# with $1

Any anchor: #((?:^|[^_])_)_+# with $1

Upvotes: 0

Marc B
Marc B

Reputation: 360652

preg_replace('/_+/', '_', $string);

thought for something so simple, you'd get better performance from str_replace().

Upvotes: 5

Dumbo
Dumbo

Reputation: 14112

you can try replacing _ with space using 'str_replace'and then trim spaces them at right side! and then add a _ at the end of string. I dont know a direct way sorry! imo this is faster than regex

Upvotes: 0

Related Questions