2013-03-11 75 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'