Replace and inserting strings within .txt files with the use of regex

Thomas Jollans thomas at jollans.com
Sun Aug 8 12:13:10 CEST 2010


On 08/08/2010 11:21 AM, Νίκος wrote:
> Please help me adjust it, if need extra modification for more php tags
> replacing.

Have you tried it ? I haven't, but I see no immediate reason why it
wouldn't work with multiple PHP blocks.

> #!/usr/bin/python
> 
> import cgitb; cgitb.enable()
> import cgi, re, os
> 
> print ( "Content-type: text/html; charset=UTF-8 \n" )
> 
> 
> id = 0  # unique page_id
> 
> for currdir, files, dirs in os.walk('data'):
> 
>     for f in files:
> 
>         if f.endswith('php'):
> 
>             # get abs path to filename
>             src_f = join(currdir,f)
> 
>             # open php src file
>             f = open(src_f, 'r')
>             src_data = f.read()         # read contents of PHP file
>             f.close()
>             print 'reading from %s' % src_f
> 
>             # replace tags
>             src_data = src_data.replace('<%', '')
>             src_data = src_data.replace('%>', '')

Did you read the script before posting? ;-)
Here, you remove ASP-style tags. Which is fine, PHP supports them if you
configure it that way, but you probably didn't. Change this to the start
and end tags you actually use, and, if you use multiple forms (such as
<?php vs <?), then add another line or two.

>             print 'replacing php tags'
> 
>             # add ID
>             src_data = ( '<!-- %d -->' % id ) + src_data
>             id += 1
>             print 'adding unique page_id'
> 
>             # create new file with .html extension
>             src_file = src_file.replace('.php', '.html')
> 
>             # open newly created html file for insertid data
>             dest_f = open(src_f, 'w')
>             dest_f.write(src_data)      # write contents
>             dest_f.close()
>             print 'writing to %s' % dest_f
> 



More information about the Python-list mailing list