Forum Moderators: coopster

Message Too Old, No Replies

regex problem

         

sebbothebutcher

10:18 pm on Jan 24, 2005 (gmt 0)

10+ Year Member



hi!
i wanted to create a regex that moves underscores from the beginning of a word to the end of a word. they look like this:

search regex : "(_+)([a-zA-Z0-9]+)"
replace regex: "$2$1"

now this works, but in case the regex encounters something like
"foo_bar"
it replaces it with
"foobar_"
.
since i'm fairly new to regexes, i can't figure it out myself how to get rid of that problem.
any help would be appreciated!
thanks in advance!

brotherhood of LAN

10:46 pm on Jan 24, 2005 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



This should do it, the ^ and $ anchors are for beginning and end of $subject, the ¦ is equal to a literal "or"

preg_replace("/(^_¦_$)/",'',$subject);

mincklerstraat

9:46 am on Jan 25, 2005 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



I think I'd try something like this:

$subject = preg_replace('#\W+_([a-zA-Z]+)\W+#', '$1.'_', $subject);

sebbothebutcher

5:25 pm on Jan 25, 2005 (gmt 0)

10+ Year Member



well... what i simply want is this:

_foobar ---> foobar_
foobar_ ---> foobar_ (stays the same)
foo_bar ---> foo_bar (stays the same)
_foobar_ ---> _foobar_ (stays the same)

for every case, the number of underscores should be anything > 0, and the string that is being replaced can occur ANYWHERE in the text. (for this specific problem, it's C++ code i'm dealing with)

valder

6:38 pm on Jan 25, 2005 (gmt 0)

10+ Year Member



the ¦ is equal to a literal "or"

Mostly right, except they have different precedence [php.net], which means that in some situations you may prefer one over the other.

mincklerstraat

6:34 pm on Jan 26, 2005 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



You try:

$subject = preg_replace('#\W+(_+)([a-zA-Z]+)\W+#', '$2$1', $subject);

?

brotherhood of LAN

6:42 am on Jan 27, 2005 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



valder, I hadn't realised I'd used PHP terminology there, thanks for clearing it up, I was thinking more literally [dictionary.reference.com]!

seo I misread your post (or rather rushed reading it) to begin with...

Just commenting on mincklerstraat's regex, I'd go along with what he has, though in your example you did mention underscores in the middle of words (that you don't want them replaced), which the above regex doens't take into account.

$subject = preg_replace('#\W+(_+)([a-zA-Z\-_0-9]+)\W+#', '$2$1', $subject);

It all depends on what you want to consitute as a "word". I've added a dash to qualify as a "word" character, you might want to include an apostrophe too.