Page 1 of 1

help with regular expression

Posted: Thu Dec 30, 2004 8:51 am
by jasongr
Hello

I would like to use ereg_repace to replace any occurrence of the '_' letter (that isn't preceded by a \) by a '?'
for example the string 'test_' should be converted to 'test?'
but the string 'test\_' should not be matched by the pattern and thus NOT be replaced to 'test\?'

this is what I tried:

Code: Select all

$string = ereg_replace('^[\\]_', '?', $string);
but obviously this isn't working

any help would be appreciated

Posted: Thu Dec 30, 2004 9:15 am
by feyd

Code: Select all

<?php

$text = "test_
test\_";

echo preg_replace('#(?<!\\\\\\\\)_#', '?', $text);

?>

Code: Select all

test?
test\_

Posted: Thu Dec 30, 2004 3:51 pm
by tomtomtom
"^" goes into the brackets to negate the expression.

Code: Select all

$string = ereg_replace('(&#1111;^\])_', '\\1?', $string);

Posted: Thu Dec 30, 2004 4:15 pm
by feyd
that I believe then requires at least 2 characters in the string to work.

Posted: Thu Dec 30, 2004 4:32 pm
by tomtomtom
Indeed it does. Your version is much faster anyway. Mine just illustrates the misplaced ^.

Posted: Thu Dec 30, 2004 4:37 pm
by feyd
quite true. :)