help with regular expression

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
jasongr
Forum Contributor
Posts: 206
Joined: Tue Jul 27, 2004 6:19 am

help with regular expression

Post 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
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

Code: Select all

<?php

$text = "test_
test\_";

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

?>

Code: Select all

test?
test\_
tomtomtom
Forum Newbie
Posts: 8
Joined: Tue Dec 28, 2004 12:39 pm

Post by tomtomtom »

"^" goes into the brackets to negate the expression.

Code: Select all

$string = ereg_replace('(&#1111;^\])_', '\\1?', $string);
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

that I believe then requires at least 2 characters in the string to work.
tomtomtom
Forum Newbie
Posts: 8
Joined: Tue Dec 28, 2004 12:39 pm

Post by tomtomtom »

Indeed it does. Your version is much faster anyway. Mine just illustrates the misplaced ^.
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

quite true. :)
Post Reply