preg_replace(mixed $pattern,mixed $replacement,mixed $subject [, int $limit = -1 [, int &$count ]])主題為匹配搜索模式,替換要搜索的模式,它可以是一個字符串或一個字符串數組.
電子修飾符使preg_replace函數()替代后,適當引用作為參數是php代碼進行替換,提示:請確保置換構成一個有效的php代碼字符串,否則php將在包含preg_replace函數線()解析錯誤.
返回值:preg_replace函數()返回一個數組,如果這個問題的參數是一個數組或一個字符串,否則,如果找到匹配,新問題會產生,否則將返回主題不變或null如果發生錯誤.
實例一,代碼如下:
- $string = 'april 15, 2003';
- $pattern = '/(w+) (d+), (d+)/i';
- $replacement = '${1}1,$3';
- echo preg_replace($pattern, $replacement, $string);
實例二,代碼如下:
- $string = 'the quick brown fox jumped over the lazy dog.';
- $patterns = array();
- $patterns[0] = '/quick/';
- $patterns[1] = '/brown/';
- $patterns[2] = '/fox/';
- $replacements = array();
- $replacements[2] = 'bear';
- $replacements[1] = 'black';
- $replacements[0] = 'slow';
- echo preg_replace($patterns, $replacements, $string);
通過ksorting模式和替代,我們應該得到我們想要的,代碼如下:
- ksort($patterns);
- ksort($replacements);
- echo preg_replace($patterns, $replacements, $string);
更換幾個值,代碼如下:
- $patterns = array ('/(19|20)(d{2})-(d{1,2})-(d{1,2})/',
- '/^s*{(w+)}s*=/');
- $replace = array ('//', '$ =');
- echo preg_replace($patterns, $replace, '{startdate} = 1999-5-27');
過濾所有html標簽,代碼如下:
- preg_replace("/(</?)(w+)([^>]*>)/e",
- "'/1'.strtoupper('/2').'/3'",
- $html_body);
過濾所有script,代碼如下:
- $user_agent = "mozilla/4.0 (compatible; msie 5.01; windows nt 5.0)";
- $ch = curl_init(); // initialize curl handle
- curl_setopt($ch, curlopt_url, $url); // set url to post to
- curl_setopt($ch, curlopt_failonerror, 1); // fail on errors
- curl_setopt($ch, curlopt_followlocation, 1); // allow redirects
- curl_setopt($ch, curlopt_returntransfer,1); // return into a variable
- curl_setopt($ch, curlopt_port, 80); //set the port number
- curl_setopt($ch, curlopt_timeout, 15); // times out after 15s
- curl_setopt($ch, curlopt_useragent, $user_agent);
- $document = curl_exec($ch);
- $search = array('@<script[^>]*?>.*?</script>@si', // strip out javascript教程 www.111cn.net
- '@<style[^>]*?>.*?</style>@siu', // strip style tags properly
- '@<[/!]*?[^<>]*?>@si', // strip out html tags
- '@<![ss]*?–[ ]*>@', // strip multi-line comments including cdata
- '/s{2,}/',
- );
- $text = preg_replace($search, " ", html_entity_decode($document));
- $pat[0] = "/^s+/";
- $pat[2] = "/s+$/";
- $rep[0] = "";
- $rep[2] = " ";
- $text = preg_replace($pat, $rep, trim($text));
- //開源代碼Vevb.com
- return $text;
- }
此函數接受一個url并返回頁面的純文本版本,它使用curl來檢索網頁,一個正則表達式的組合,以去除所有不必要的空白,這個功能甚至剝奪了從形式和script標記,這是由php函數忽略,如用strip_tags,他們地帶唯一的標記文本,留下完整的文字在中間.
正則表達式被分為兩個階段,以避免刪除單,也由 s的匹配,回車,但仍然刪除所有空白行和多個換行符或空格,修整手術進行了2個階段進行.
新聞熱點
疑難解答