Forum und email

Regular Expression Functions (POSIX Extended)

介紹

Tip

PHP also supports regular expressions using a Perl-compatible syntax using the PCRE functions. Those functions support non-greedy matching, assertions, conditional subpatterns, and a number of other features not supported by the POSIX-extended regular expression syntax.

Warning

These regular expression functions are not binary-safe. The PCRE functions are.

Regular expressions are used for complex string manipulation. PHP uses the POSIX extended regular expressions as defined by POSIX 1003.2. For a full description of POSIX regular expressions see the » regex man pages included in the regex directory in the PHP distribution. It's in manpage format, so you'll want to do something along the lines of man /usr/local/src/regex/regex.7 in order to read it.

需求

建立這個延伸不需要任何外部程式庫。

安裝

Warning

Do not change the TYPE unless you know what you are doing.

To enable regexp support configure PHP --with-regex[=TYPE]. TYPE can be one of system, apache, php. The default is to use php.

Windows 版本的 PHP 已內建此延伸的支援﹐所以你毋須再載入附加的延伸來使用這些功能。

執行時期組態

php.ini中沒有定義此延伸的組態指令。

資源類型

這個延伸沒有定義任何資源。

預先定義常數

這個延伸沒有定義任何常數。

範例

Example#1 Regular Expression Examples

<?php
// Returns true if "abc" is found anywhere in $string.
ereg("abc"$string);            

// Returns true if "abc" is found at the beginning of $string.
ereg("^abc"$string);

// Returns true if "abc" is found at the end of $string.
ereg("abc$"$string);

// Returns true if client browser is Netscape 2, 3 or MSIE 3.
eregi("(ozilla.[23]|MSIE.3)"$_SERVER["HTTP_USER_AGENT"]);

// Places three space separated words into $regs[1], $regs[2] and $regs[3].
ereg("([[:alnum:]]+) ([[:alnum:]]+) ([[:alnum:]]+)"$string$regs); 

// Put a <br /> tag at the beginning of $string.
$string ereg_replace("^""<br />"$string); 
 
// Put a <br /> tag at the end of $string.
$string ereg_replace("$""<br />"$string); 

// Get rid of any newline characters in $string.
$string ereg_replace("\n"""$string);
?>

參考

For regular expressions in Perl-compatible syntax have a look at the PCRE functions. The simpler shell style wildcard pattern matching is provided by fnmatch().

Table of Contents

  • ereg_replace — Replace regular expression
  • ereg — Regular expression match
  • eregi_replace — Replace regular expression case insensitive
  • eregi — Case insensitive regular expression match
  • split — Split string into array by regular expression
  • spliti — Split string into array by regular expression case insensitive
  • sql_regcase — Make regular expression for case insensitive match