Topic: Regular Expressions help.

Okay, I'm having some trouble with Regex. I have this string:

'What is %? <input name="auth">'

I have this Regex applied to this string:

Matches all % characters not followed by a \
preg_replace('/[^\\\\]%/', $this->literal, $formatting);

This is the output:

What isfive times three?

I want the space to remain between the 'is' and 'five', so essentially, the output should be: 'What is five times three?'. How can I do this? What am I doing wrong?

Re: Regular Expressions help.

http://us2.php.net/sprintf
?

Re: Regular Expressions help.

I don't really want to use sprintf for this. Meh, I give up. I'll just use str_replace. Thanks though.

Re: Regular Expressions help.

I don't know about php's preg's... my experience with php preg functions has been @#$!%@@ #$%!!#@%$^%# #@$ $#@$@# @$$# #@$&^^$#$

I'd try something like this:

preg_replace_all('/([^\\])\%/', '\2five', 'What is %?');

Also what smarty said is probably right. At one point perl was alot faster the sed at processing strings, since perl was designed (originally) for just that. php is still relatively young, and I think the preg functions were just thrown in by some guy who never used perl in the first place. sprintf is probably much more efficient. Heck even the php docs tell you to avoid the preg function set... And why in the world are the 10 "perl compitible" functions for 2 different perl syntactical statements? I want to kill the fool who decided preg's don't need the /regex/[modifyers]...

str_replace('%', 'five', 'what is %?');
str_replace('\\five', '%', 'what is five?');

Should do the trick in half the time.

echo "deadram"; echo; fortune;

5 (edited by mustbeDreaming 2007-03-08 11:14)

Re: Regular Expressions help.

What about

@(?<!\\\)%@

or if you want it the other way around:

@%(?!\\\)@

check http://wiki.tcl.tk/9384

Re: Regular Expressions help.

Dunno if you figured it out already or not, but figured I would post anyway in case someone else had this problem.

Since your pattern is two characters (read "any character except backslash followed by a percent sign"), both characters will be replaced. You need to put the first character back in.  In the pattern, put parenthesis around the first character, and then prefix the replacement with \1.

preg_replace('/([^\\\\])%/', \1 . $this->literal, $formatting);