Need regexp help to remove css code - regex

How could we use regexp (replace) to find all occurrences of the following CSS
code in a long string and remove them (the XMP code is what I added)? Thanks.
<xmp>
body { font-family : "Courier New", Courier, monospace; font-size : 9pt; valign : top; text-align : left; line-height: 9pt }
td {
font-family : "Courier New", Courier, monospace; font-size : 9pt; valign : top; text-align : left; line-height: 9pt }
</xmp>

Assuming that the string you provided is inside myString and all the css code is inside cssString.
cssString = cssString.replace(myString, '');

If you want to remove the "\\ \\" along with the content contained within it ! This is how you do in python:
s="<xmp> your css code</xmp>"
s=re.sub("<xmp>.*</xmp>", " ",s)
output:
>>>s
''
In the code above i am substituting everything that starts with tag and $'.*' basically tells the python interpreter to include all the characters until the end tag and substitutes the entire thing with $" ".
if you want to remove just the content of the tags then:
s="<xmp> your css code</xmp>"
code_inside_xmptag=re.search("<xmp>(*.)</xmp>",string)
s=re.sub(code_inside_xmptag.group(1)," ",string)
Output:
>>>s
<xmp> </xmp>
Over here i am basically searching for the tags and creating a group for the content contained.
I am passing that as the string to be replaced/substituted.
You can read more about Regular Expressions in python : Here

Related

Put a quotes around current list item in a SASS loop

I have this on Friday evening which I've stacked with. Trying to add quotes around the current item $breakpoint and produce output like
a[data-x="bp1"]
a[data-x="bp2"]
... and so on
but instead, as you guess I'm having a[data-x=bp2]
$spacings: "8%", "9%", "10%", "11%", "13%", "14%";
#each $breakpoint in $breakpoints {
a[data-x=#{$breakpoint}] {
.span {
margin-left: nth($spacings, index($breakpoints, $breakpoint));
}
}
}
any help will be highly appreciated!
You need to escape your quotation marks with \ to keep them in the compiled CSS.
You can either write the names of your breakpoints as:
$breakpoints: "\"bp1\"", "\"bp2\"", "\"bp3\"", "\"bp4\"", ...;
Or simply write your selector as a[data-x=#{"\"#{$breakpoint}\""}]:
$spacings: "8%", "9%", "10%", "11%", "13%", "14%";
$breakpoints: bp1, bp2, bp3, bp4, pb5, bp6; // Quotation marks not needed
#each $breakpoint in $breakpoints {
a[data-x=#{"\"#{$breakpoint}\""}] {
.span {
margin-left: nth($spacings, index($breakpoints, $breakpoint));
}
}
}
Another solution is to use single quotations marks around your variable (or breakpoints names) and then unquote():
a[data-x=#{unquote('"#{ $breakpoint }"')}]

Regular expression for parsing out CSS rules block

Has snippet of CSS:
.__chat.__32x32 {
color: white;
background: url({ANYNAME:anyName}Images/icons/32x32/chat.png{ANYNAME}) no-repeat;
}
The problem: need to parse out block of css(selector+rules block). Bu closing curly bracket in url considered by my pattern as closing for rules block. All the tries with lookarounds at this point did not give me a success.
Question: How to make pattern consider construction {anyname} as part of the match string if it is inside url: rule or rules block?
var parser = new Regex(#"([a-z0-9\s,*\""\[\]=\.\:#_\-#]+){((?>[^}]+|(?:(?<={ROOT)|(?<={VERSION))})*)}|(\/\*(?:(?:(?!\*\/)[\S\s])+)\*\/)", RegexOptions.Multiline | RegexOptions.IgnoreCase);
MatchCollection matches;
matches = parser.Matches(fullContent);
foreach (Match match in matches)
{
if (match.Value.IndexOf("/*") > -1)
{
var cssComment = new CssComment(match.Value);
_cssElements.Add(cssComment);
}
else
{
var cssBlock = new CssBlock(match.Groups[1].Value.Trim(), match.Groups[2].Value.Trim());
_cssElements.Add(cssBlock);
}
}
Please try this:
[.#]?[\w\s.<>]+{(\n.*)+?(?=\n}\n)\n}
it matches whole block (selector+inside code). You may have to make some alterations in the selector part [.#]?[\w\s.<>] to make it work for your problem.

Remove unwanted characters from URL

I have used GetRouteUrl to create SEO friendly URLs but I now want to remove %20 ie spaces and replace with a dash ("-"). An example page from my website is shown below. I want to Title variable to be "madonna-item" and not "Madonna%20Item".
/ProductsByDepartment/Gracya/Madonna/Madonna%20Item?CategoryId=9&productId=8&departmentId=4
I have create a class (StringHelpers) to fix the url but I don't know where to call FixUrl
Public static class StringHelpers
{
public static string FixUrl(this string url)
{
string encodedUrl = (url ?? "").ToLower();
encodedUrl = Regex.Replace(encodedUrl, #"\+", "and");
encodedUrl = encodedUrl.Replace("'", "");
encodedUrl = Regex.Replace(encodedUrl, #"[^a-z0-9]", "-");
return encodedUrl;
}
}
The code which contains the link to update is below. I want to use FixUrl on the Title field, but this does not work.
Please can you advise me how to use FixUrl?
<td class="Product_title" height="20px" width="180px">
<a href='<%#: GetRouteUrl("ProductExtraRoute", new {CategoryId = Eval("catId"), productId = Eval("productId"), departmentId = Eval("depId"), Title = Eval("Title")}).FixUrl()%>' class="Product">
<asp:Literal ID="literal2" runat="server" Text='<%# Eval(("Title").FixUrl()) %>'></asp:Literal>
Try decodeURIComponent
Check this http://www.w3schools.com/jsref/jsref_decodeuricomponent.asp
After this replace all speces with -

Multiple Regex-replace (In Aptana Studio 3), depending on match

Since mysql_* is going deprecated, I was thinking of an easy way to replace all deprecated code.
Here is my regex; whereas find is what I want to find and repl is what I want to replace it with.
$__db is my declared mysqli_connect-variable
Change MySQL into MySQLi
--
find: mysql_select_db\(([\$"a-zA-Z0-9_]+)\)
repl: \$__db->select_db($1)
--
find: mysql_fetch_object\((\$[a-zA-Z0-9_]+)\)
repl: $1->fetch_object()
--
find: mysql_fetch_array\((\$[a-zA-Z0-9_]+)\)
repl: $1->fetch_array()
--
find: mysql_num_rows\((\$[a-zA-Z0-9_]+)\)
repl: $1->num_rows
--
find: mysql_free_result\((\$[a-zA-Z0-9_]+)\)
repl:
--
find: mysql_query
repl: \$__db->query
--
find: mysql_error\(\)
repl: mysqli_error\(\)
--
find: ([\$a-zA-Z0-9_]+) = mysql_result\(([\$a-zA-Z0-9_]+), (\d+)\)
repl: \$row = $2->fetch_array();\r\n$1 = \$row[$3]
And my question would be, can I run multiple regex-replaces (so that I can replace all code at the same time)?
I know that I can use pipe | to separate the find-part, but how does it work with the replace-part?
I haven't found a way to make a macro in Aptana Studio 3.
This became my solution, with tips from HamZa (Thanks!)
I created a script, that iterates over a directory of choosing (Specified in $dir)
We also get to say what we're looking for in the files with $lookFor
I added some comments in the code, so you can follow what I do. This WON'T solve function-db's though.
So if you have classes with DB-connections you'll have to add something for functions.
Right now this script won't change your files (I commented it out, so you can use it to just browse through your code with the "recommended" changes)
And also.. I haven't made it so the script prepares statements.
(That is step two, this was just to fix things that would break when mysql_* gets removed)
The result will look something like this: (Actually showing that missing function I talked about.. I'll have to add global $__db; into each function
And then finally! Here's the code.
<?
/*IGNORE-MYSQL*/
function startsWith($haystack, $needle)
{
return strpos($haystack, $needle) === 0;
}
function endsWith($haystack, $needle)
{
return substr($haystack, -strlen($needle)) == $needle;
}
function doFlush()
{
#flush();
#ob_flush();
}
function runMySQLToMySQLi_replace($str, $useBoldShow = false, $replace = true)
{
$catchVars = '\$"\'a-zA-Z0-9_\.\*\->,\[\] ';
$regexTests = Array();
$regexTests['(?:['.$catchVars.']+\s?=\s?)?mysql_connect\((['.$catchVars.']+),\s?(['.$catchVars.']+),\s?(['.$catchVars.']+)\)'] = '\$__db = mysqli_connect($1, $2, $3)';
$regexTests['mysql_select_db\((['.$catchVars.']+)(?:,\s?['.$catchVars.']+)?\)'] = '\$__db->select_db($1)';
$regexTests['mysql_query\((['.$catchVars.'\(\)=]+)(?:,\s?['.$catchVars.']+)?\)'] = '\$__db->query($1)';
$regexTests['mysql_errno\(\)'] = '\$__db->errno';
$regexTests['mysql_error\(\)'] = '\$__db->error';
$regexTests['mysql_error\((['.$catchVars.']+)\)'] = '\$__db->error';
$regexTests['mysql_fetch_object\((['.$catchVars.']+)\)'] = '$1->fetch_object()';
$regexTests['mysql_fetch_row\((['.$catchVars.']+)\)'] = '$1->fetch_array()';
$regexTests['mysql_fetch_array\((['.$catchVars.']+)\)'] = '$1->fetch_array()';
$regexTests['mysql_fetch_assoc\((['.$catchVars.']+)\)'] = '$1->fetch_assoc()';
$regexTests['mysql_num_rows\((['.$catchVars.']+)\)'] = '$1->num_rows';
$regexTests['mysql_free_result\((['.$catchVars.']+)\)'] = '$1->free()';
$regexTests['mysql_insert_id\(\)'] = '\$__db->insert_id';
$regexTests['(['.$catchVars.']+) = mysql_result\((['.$catchVars.']+), (\d+)\)'] = "\$row = $2->fetch_array(); $1 = \$row[$3]";
$tmpVal = $str;
foreach($regexTests as $reg => $rep)
{
$match = preg_match("/" . $reg . "/i", $tmpVal);
if($match)
{
if($replace)
$tmpVal = preg_replace("/" . $reg . "/i", ($useBoldShow ? "[{b}]" : "") . $rep . ($useBoldShow ? "[/{b}]" : ""), $tmpVal);
else
$tmpVal = preg_replace("/" . $reg . "/i", ($useBoldShow ? "[{b}]" : "") . "$0" . ($useBoldShow ? "[/{b}]" : ""), $tmpVal);
}
}
return $tmpVal;
}
?>
<html>
<head>
<style>
body { margin: 0; padding: 0; }
.mysql_found { background-color: mistyrose; padding: 10px; border: 1px solid #c9c9c9; border-radius: 5px; margin: 10px; }
.no_select {
-webkit-touch-callout: none;
-webkit-user-select: none;
-khtml-user-select: none;
-moz-user-select: moz-none;
-ms-user-select: none;
user-select: none;
display: inline-block;
}
</style>
</head>
<body>
<pre><?
// Directory to search in
$dir = "/dir/to/search/in/";
$objects = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($dir), RecursiveIteratorIterator::SELF_FIRST);
// What we are looking for in all files
$lookFor = "mysql_";
foreach($objects as $name => $object)
{
// Ensure that it is PHP-files we're going through
if(endsWith($object->getFilename(), '.php'))
{
// Get all contents
$contents = file_get_contents($object->getPathname());
// Split it into rows
$rowSplit = preg_split('/$\R?^/m', $contents);
// Check the contents for $lookFor
if(strpos($contents, $lookFor) > 0 && strpos($contents, "/*IGNORE-MYSQL*/") === false)
{
echo "<div class=\"mysql_found\">\"" . $lookFor . "\" found in: " . $object->getPathname() . "\n";
echo "<hr noshade=\"noshade\" />\n";
echo "Source code:\n";
$lCount = 1;
foreach($rowSplit as $row)
{
echo "<div class=\"no_select\" unselectable=\"on\">" . str_pad($lCount++, strlen(count($rowSplit)), " ", STR_PAD_LEFT) . ": </div>" . str_replace(Array("[{b}]", "[/{b}]"), Array("<b style=\"background-color: #cfaaaa;\">", "</b>"), htmlentities(runMySQLToMySQLi_replace($row, true, false))) . "\n";
}
echo "\n\n";
$lCount = 1;
echo "Fixed code:<br /><br />";
$doneCode = "";
foreach($rowSplit as $row)
{
echo "<div class=\"no_select\" unselectable=\"on\">" . str_pad($lCount++, strlen(count($rowSplit)), " ", STR_PAD_LEFT) . ": </div>" . str_replace(Array("[{b}]", "[/{b}]"), Array("<b style=\"background-color: #cfaaaa;\">", "</b>"), htmlentities(runMySQLToMySQLi_replace($row, true))) . "\n";
// This is the code that actually does the replacing.
$doneCode .= runMySQLToMySQLi_replace($row) . "\n";
}
// This is commented out, since I want to make sure it works before I accept some changes.
// I actually tried it on 3 files without problems.
//if(isset($_GET['Accepted']))
// file_put_contents($object->getPathname(), $doneCode);
echo "</div>";
}
}
doFlush();
}
?></pre>
</body>
</html>
If you want to ask me something about this code, do it. :)

Tinymce editor gallery plugin Regexp problem?

I am using tinymce editor for inserting contents to mysql.
I have changed wordpress gallery editor plugin according to my system.
If there is gallery code in content. I convert this code to a symbolic photo, so that user understand there is a gallery , in stead of seeing a code. Like wordpress does.
If there is only 1 gallery in content, i convert this code to image successfully, but if there is more than 1 gallery it fails.
How can i convert all {gallery} code into a symbolic image before saving to db and convert these photos back to {gallery} code again while inserting or updating into mysql.
I am so bad on regular expression.
I think do_gallery RegExp has mistake. How should i change this.
initalising editor like:
ed.onBeforeSetContent.add(function(ed, o) {
ed.dom.loadCSS(url + "/css/gallery.css");
o.content = t._do_gallery(o.content);
});
ed.onPostProcess.add(function(ed, o) {
if (o.get)
o.content = t._get_gallery(o.content);
});
My "do and get gallery" codes like that:
_do_gallery : function(co) {
return co.replace(/\{gallery([^\]]*)\}/g, function(a,b){
var image = '<img src="gallery.gif" class="wpGallery mceItem" title="gallery'+tinymce.DOM.encode(b)+'" />';
console.log(image);
return image;
});
},
_get_gallery : function(co) {
function getAttr(s, n) {
n = new RegExp(n + '="([^"]+)"', 'g').exec(s);
return n ? tinymce.DOM.decode(n[1]) : '';
};
return co.replace(/(?:<p{^>}*>)*(<img[^>]+>)(?:<\/p>)*/g, function(a,im) {
var cls = getAttr(im, 'class');
if ( cls.indexOf('wpGallery') != -1 )
return '<p>{'+tinymce.trim(getAttr(im, 'title'))+'}</p>';
return a;
});
}
If Content is:
<p>Blah</p>
<p>{gallery Name="gallery1" id="82" galeryID="15" sizeId="6" galery_type="list"}</p>
<p>test</p>
this is ok
<img src="gallery.gif" class="wpGallery mceItem" title="gallery Name="tekne1" id="82" galeryID="15" sizeId="6" galery_type="liste"" />
But, if content is:
<p>Blah</p>
<p>{gallery Name="gallery1" id="82" galeryID="15" sizeId="6" galery_type="list"}</p>
<p>test</p>
<p>{gallery Name="gallery2" id="88" galeryID="11" sizeId="1" galery_type="slide"}</p>
<p>test2</p>
it logs
<img src="gallery.gif" class="wpGallery mceItem" title="gallery Name="gallery1" id="82" galeryID="15" sizeId="6" galery_type="list"}</p> <p>test</p> <p>{gallery Name="gallery2" id="88" galeryID="11" sizeId="1" galery_type="slide"" />
I hope i could explain my problem
Thank you.
I suspect that your original regex is a typo, looks like a missing Shift when you hit the ]. Try this:
/\{gallery([^\}]*)\}/g
Then the ([^\}]*) part will (greedily) eat up any sequence of characters that aren't }; your original one would consume any sequence of character that didn't include a ] and the result is that you'd grab everything between the first { and the last } rather than just grabbing the text between pairs of braces.