Re: RegExp question: how to add a number?

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



On 14 October 2010 21:42, Andre Polykanine <andre@xxxxxxxx> wrote:
> 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?
> Thanks!

Can you adapt this ...

<?php
$s_Text = 'Re: A dummy subject.';

foreach(range(1,10) as $i_Test)
	{
	echo $s_Text = preg_replace_callback
		(
		'`^Re(\[(\d++)\])?:`',
		function($a_Match)
			{
			if (count($a_Match) == 1)
				{
				$i_Count = 2;
				}
			else
				{
				$i_Count = 1 + $a_Match[2];
				}
			return "Re[$i_Count]:";
			},
		$s_Text
		), PHP_EOL;
	}


Outputs ...

Re[2]: A dummy subject.
Re[3]: A dummy subject.
Re[4]: A dummy subject.
Re[5]: A dummy subject.
Re[6]: A dummy subject.
Re[7]: A dummy subject.
Re[8]: A dummy subject.
Re[9]: A dummy subject.
Re[10]: A dummy subject.
Re[11]: A dummy subject.


-- 
Richard Quadling
Twitter : EE : Zend
@RQuadling : e-e.com/M_248814.html : bit.ly/9O8vFY

-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



[Index of Archives]     [PHP Home]     [Apache Users]     [PHP on Windows]     [Kernel Newbies]     [PHP Install]     [PHP Classes]     [Pear]     [Postgresql]     [Postgresql PHP]     [PHP on Windows]     [PHP Database Programming]     [PHP SOAP]

  Powered by Linux