RE: [PHP] RegExp question: how to add a number?
| From: | Ford, Mike | Date: | Fri, 15 Oct 2010 09:16:35 +0000 |
| Subject: | RE: [PHP] RegExp question: how to add a number? | ||
| References: | 1 | Groups: | php.general |
| Request: | Send a blank email to php-general+get-308733@lists.php.net to get a copy of this message | ||
> -----Original Message-----
> From: Andre Polykanine [mailto:andre@oire.org]
> Sent: 14 October 2010 21:42
>
> Hi everyone,
> I hope you're doing well (haven't written here for a long time :-)).
> The question is as follows: I have a regexp that would do the
> following. If the string begins with "Re:", it will change the
> beginning to "Re[2]:"; if it doesn't, then it would add "Re:" at the
> beginning. But (attention, here it is!) if the string starts with
> something like "Re[4]:", it should replace it by "Re[5]:".
> Here's the code:
>
> $start=mb_strtolower(mb_substr($f['Subject'], 0, 3));
> if ($start=="re:") {
> $subject=preg_replace("/^re:(.+?)$/usi", "re[2]:$1",
> $f['Subject']);
> } elseif ($start=="re[") {
> // Here $1+1 doesn't work, it returns "Re[4+1]:"!
> $subject=preg_replace("/^re\[(\d+)\]:(.+?)$/usi", "re[$1+1]:$2",
> $f['Subject']);
> } else {
> $subject="Re: ".$f['Subject'];
> }
>
> I know there actually exists a way to do the numeral addition
> ("Re[5]:", not "Re[4+1]:").
> How do I manage to do this?
This looks like a job for the "e" modifier (see http://php.net/manual/en/reference.pcre.pattern.modifiers.php,
and example #4 at http://php.net/preg_replace). Something
like:
$subject = preg_replace("/^re\[(\d+)\:](.+?)$/eusi",
"'re['.(\\1+1).']:\\2'", $f['Subject']);
Cheers!
Mike
--
Mike Ford,
Electronic Information Developer, Libraries and Learning Innovation,
Leeds Metropolitan University, C507 City Campus,
Woodhouse Lane, LEEDS, LS1 3HE, United Kingdom
Email: m.ford@leedsmet.ac.uk
Tel: +44 113 812 4730
To view the terms under which this email is distributed, please go to http://disclaimer.leedsmet.ac.uk/email.htm