API

Returns the matches of a perl regular expression in an array (getting rid of the unnecessary first element that preg_match generates) ; the result is returned in a scalar if one variable is matched (\1) and alternatively in array. The matches can also be replaced.

$regex

string

The full regular expression (including options such as "/.../ice").

$subject

mixed

The subject is a string or an array of strings that is subject to modification (passed in by reference).

$replace

bool

The optional replacement string (accepts variables such as "1").

$all

bool

Whether one or all instances should be matched/replaced (default: all=false).

$alwaysArray

bool

By default when only one variable is matched, it is returned as a scalar (e.g. by default"/ (a) /" is returned as scalar, "/ (a) (b) /" as an array). Setting this to true will always return the matches as an array.

returns

mixed

The match or matches. This can be a string, an array of strings or an array of an array of strings (match all). Null when no matches.

Example

This example works on the string: "[USA] Gold, [Netherlands] Silver, [Canada] Bronze"

Conclusion

Using RUtil::preg code will reduce the amount of code you produce. Which will, in the long run, save (a) programming hours, (b) reduce bugs and (c) increase execution performance (less code to put in memory). The subject is changed by reference. This can be annoying because you need to assign a temporary var if you don't want to change the subject. Always use preg_replace when you don't care about returning matches.