|
Posted by Steve on 02/23/07 03:54
<dennis.sprengers@gmail.com> wrote in message
news:1172189473.962693.113080@m58g2000cwm.googlegroups.com...
| Consider the following array and string:
|
| $trail = array('products/veggies', 'products', 'services/cleaning');
| $path = 'products/veggies/1243/more';
|
| I am trying to write a function that matches $path with a value in
| $trail. If no match is found, it should chop off "more" and compare
| again. Then, chop off "1243" and compare again. Now a match is found:
| "products/veggies". The function should return true.
|
| Let's take another example: $path = 'services/industrial/gardening'.
| There is no match for $path in $trail. Chopping off "gardening" leaves
| "services/industrial". Again, no match. Chopping off "industrial"
| leaves "services". No match will be found; the function should return
| false.
|
| This is what I have so far:
|
| function in_trail($path) {
| global $trail;
|
| while ($path && !in_array($path, $trail)) {
| $path = substr($path, 0, strrpos($path, '/'));
| }
|
| return $path ? true : false;
|
| }
|
| But this function always returns true! Could someone explain this to
| me and tell me how to fix it? Your help is much appreciated :-)
because $path will eventually be a value without a '/', yes? that means
strrpos will return -1. consequently, $path will equal the last letter of
the final value. in that case, it will always be true (not 0, not null, not
'', etc.). ex.
$path = 'products/veggies/1234/more';
//your while function processing here
echo '<pre>' . $path '</pre>';
browser displays the letter s. even if you began your path with a '/' (as in
'/products/veggies/'), the final value of $path would be '/'...which is
true. i've not run your code, but this is what i immediately see as faulty
in the code. consider this as an alternative:
function inTrail($path, $trail)
{
if (!is_array($trail)){ return ''; }
if (!strlen($path)){ return ''; }
$match = '';
$path = explode('/', $path);
$length = count($trail);
for ($i = 0; $i < $length; $i++)
{
if ($path[$i] != $trail[$i]){ break; }
$match .= $path[$i] . '/';
}
return $match;
}
notice the missing global def. of $trail...get out of bad habits. you should
also adjust this so that you explicitly allow case-less matching or note in
the function that 'a' is not the same thing as 'A'. this evaluates to false
if $match is '', but returns the amended path as well which comes in handy
if you plan on handling the delima of one a path only partially matching the
trail...you will be able to replace the original with the ammended and end
up with what portion didn't match.
again, i'm just thinking out loud...so there may be syntax or other errors
in the code i just wrote. the code should give you an idea of what i'm
trying to express.
hth,
me
[Back to original message]
|