note 107958 added to function.preg-match
| From: | aer0s | Date: | Fri, 16 Mar 2012 21:15:16 +0000 |
| Subject: | note 107958 added to function.preg-match | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-186716@lists.php.net to get a copy of this message | ||
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
----
Server IP: 69.147.83.197
Probable Submitter: 70.43.223.178
----
Manual Page -- http://www.php.net/manual/en/function.preg-match.php
Edit -- https://master.php.net/note/edit/107958
Del: integrated -- https://master.php.net/note/delete/107958/integrated
Del: useless -- https://master.php.net/note/delete/107958/useless
Del: bad code -- https://master.php.net/note/delete/107958/bad+code
Del: spam -- https://master.php.net/note/delete/107958/spam
Del: non-english -- https://master.php.net/note/delete/107958/non-english
Del: in docs -- https://master.php.net/note/delete/107958/in+docs
Del: other reasons-- https://master.php.net/note/delete/107958
Reject -- https://master.php.net/note/reject/107958
Search -- https://master.php.net/manage/user-notes.php