Re: preg_match

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

 



Please keep the conversation on the list!

On 27 Oct 2008, at 16:06, Alex Chamberlain wrote:
-----Original Message-----
From: Stut [mailto:stuttle@xxxxxxxxx]
Sent: 27 October 2008 15:54
To: Alex Chamberlain
Cc: 'PHP General list'
Subject: Re:  preg_match

On 27 Oct 2008, at 15:46, Alex Chamberlain wrote:
Problem solved:
function __autoload($c) {
$m = array();
preg_match('/(?:^[A-Z][a-z]+)Controller/', $c, $m);
if (count($m)) {
 require_once(realpath(FS_CONTROLLER . '/' . strtolower($m[0]) .
'.inc.php'));
}
}

However (perhaps a more appropriate question), do you think there is
an
easier/better way to do this??

See, that wasn't so hard was it!!

Personally I'd have gone with something more like this...

function __autoload($class)
{
  if (substr($class, -10) == 'Controller')
  {
    // No need for realpath here, it's not doing anything useful
    // The _once is probably redundant too, but it may be required
    // depending on how your code is arranged.
    require FS_CONTROLLER.'/'.strtolower($class).'.inc.php';
  }
}

...but there's always more than one solution.

-Stut


Ok, spurred on with the success so far (but not changing the form of my code
just yet), I changed it to:

function __autoload($c) {
 $m = array();

 preg_match('/Fred(^[A-Z][a-zA-Z]+)/', $c, $m);
 if (count($m)) {
  require_once(realpath(FS_COMPONENT . '/' . strtolower($m[1]) .
'.inc.php'));
 }

 var_dump($m);

 preg_match('/(?:^[A-Z][a-z]+)Controller/', $c, $m);
 if (count($m)) {
  require_once(realpath(FS_CONTROLLER . '/' . strtolower($m[0]) .
'.inc.php'));
 }
}

With the aim of also matching anything starting with 'Fred'. It didn't work
until I took the caret ^ out:

function __autoload($c) {
 $m = array();

 preg_match('/Fred([A-Z][a-zA-Z]+)/', $c, $m);
 if (count($m)) {
  require_once(realpath(FS_COMPONENT . '/' . strtolower($m[1]) .
'.inc.php'));
 }

 var_dump($m);

 preg_match('/(?:^[A-Z][a-z]+)Controller/', $c, $m);
 if (count($m)) {
  require_once(realpath(FS_CONTROLLER . '/' . strtolower($m[0]) .
'.inc.php'));
 }
}

What I don't understand is why I needed it in one, but not in another??

If you're going to use regular expressions you need to read the manual to understand how they work. There's a whole section of the manual that covers this - go read it to understand what the ^ means!

-Stut

--
http://stut.net/

--
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