2013-03-11 71 views
4

我在PHP利特尔表示:的Python:preg_replace函数功能模拟

$search = array("'<(script|noscript|style|noindex)[^>]*?>.*?</(script|noscript|style|noindex)>'si", 
    "'<\!--.*?-->'si", 
    "'<[\/\!]*?[^<>]*?>'si", 
    "'([\r\n])[\s]+'"); 

$replace = array ("", 
    "", 
    " ", 
    "\\1 "); 

    $text = preg_replace($search, $replace, $this->pageHtml); 

我怎么没在蟒蛇跑的? re.sub

+2

是,'re.sub'。你试过了吗? – bereal 2013-03-11 05:40:19

+0

@bereal ok,我如何设置多个模式并替换为're.sub'? – 2013-03-11 05:49:12

+1

它似乎没有特别的要求,但为什么不使用'|'如例如所述[这里](http://emilics.com/blog/article/multi_replace.html)? – bereal 2013-03-11 05:56:08

回答

3

由于@bereal commented使用正则表达式模块re.sub

这里有一个简单的例子

PHP:

<?php 
echo strtolower(preg_replace('/([^A-Z])([A-Z])/', '$1_$2', 'camelCase')); 
// prints camel_case 

的Python:

>>> import re 
>>> re.sub(r'([^A-Z])([A-Z])', r'\1_\2', 'camelCase').lower() 
'camel_case'