PHPverse 2025

Voting

: min(four, two)?
(Example: nine)

The Note You're Voting On

aer0s
13 years ago
Simple function to return a sub-string following the preg convention. Kind of expensive, and some might say lazy but it has saved me time.

# preg_substr($pattern,$subject,[$offset]) function
# @author aer0s
# return a specific sub-string in a string using
# a regular expression
# @param $pattern regular expression pattern to match
# @param $subject string to search
# @param [$offset] zero based match occurrence to return
#
# [$offset] is 0 by default which returns the first occurrence,
# if [$offset] is -1 it will return the last occurrence

function preg_substr($pattern,$subject,$offset=0){
preg_match_all($pattern,$subject,$matches,PREG_PATTERN_ORDER);
return $offset==-1?array_pop($matches[0]):$matches[0][$offset];
}

example:

$pattern = "/model(\s|-)[a-z0-9]/i";
$subject = "Is there something wrong with model 654, Model 732, and model 43xl or is Model aj45B the preferred choice?";

echo preg_substr($pattern,$subject);
echo preg_substr($pattern,$subject,1);
echo preg_substr($pattern,$subject,-1);

Returns something like:

model 654
Model 732
Model aj45B

<< Back to user notes page

To Top