...

View Full Version : Regex to replace \" with " and replace " with ' (code cleaning after bad programmer)



Bawy
03-06-2003, 09:12 PM
I am cleaning a previous programmers work and am attempting to replace occurences like this:

echo "<form action=\"myform.php\" method=\"post\"><input type=\"Hidden\" name=\"Price\" value=\"".$product["price"]."\">";

Which is just ridiculous to try and make HTML adjustments to.

I would like to make a regex that replaces all occurences of " with ' except when a \ precedes it, in which case it should just drop the slash and leave the quote.

\" becomes "
" becomes '

but \" should not become '

I thought of replacing all \" with some arbitrary unicode charector that would never appear in the code and then replacing " with ' and finally from unicode charctor to " but there must be a better way with regex.

missing-score
03-06-2003, 10:41 PM
stripslashes( $code )

str_replace('\"', '"', $code);

I dont really understand, but this may help...

mordred
03-07-2003, 12:15 AM
Ok, this is going to be a backslash desaster if vBulletin intends to strip them away from my post. Anyway, let's try it:



$search = array(
'/(?<!\\\\)"/',
'/\\\\"/'
);

$replace = array(
"'",
'"'
);

print preg_replace($search, $replace, $file);


Hmh... looks okay in the preview mode... submitting...

Bawy
03-07-2003, 06:33 AM
Thanks so much, I needed to modify it slightly to work with a form result and display in the browser, but otherwise, great:


if(isset($code)) {
$code=str_replace("'","\\'",stripslashes($code));
$search = array(
'/(?<!\\\\)"/',
'/\\\\"/'
);
$replace = array(
"'",
'"'
);
echo str_replace("\n",'<br>',htmlspecialchars(preg_replace($search, $replace, $code)));
} else {
echo '<form><textarea cols=120 rows=40 name="code"></textarea><br><input type="submit"></form>';
}


uggg, here is something that is the remnants of previous manual attempts at conversion with an obvious oversight:

echo '<area coords="65,1,35,22" href="products.php?section=<?= $section ?>&sort=price">';

Any way to replace it with concat strings like

products.php?section='.$section.'&sort

There are so many variations I dunno if it is reasonable even, specifically because the previous programmers have no spacing consistancy, there appears all of the below:

<?= $section ?>
<?=$section?>
<?= $section; ?>
<?echo $section; ?>
<?echo $section?>

you get the idea...

mordred
03-07-2003, 03:13 PM
Sure that's possible



print preg_replace(
'/\<\?(\s*?echo|\=\s*?)\s*(.+?)\s*;?\s*\?\>/',
"' . \\2 . '",
$file
);


I am used to seperate string operators with a space (whitespace is good for your eyes), that's why I tailored the RegExp this way.

Bawy
03-10-2003, 10:23 PM
Thanks dude, your pretty good at regex!



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum