note 64154 deleted from function.substr by nlopess

From: Date: Sat, 08 Apr 2006 22:03:27 +0000
Subject: note 64154 deleted from function.substr by nlopess
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-107572@lists.php.net to get a copy of this message
Note Submitter: g8z at yahoo dot com ---- <?php /** * Gets the common substring from all values of $arr, starting from $offset * Courtesy of the $5 Script Archive: http://www.tufat.com */ function findcommon( $arr, $offset = 0 ) { $common = FALSE; $mlen = strlen($arr[0]); foreach($arr as $str) { if ( $mlen > strlen( $str ) ) { $mlen = strlen($str); } } for( $p = $offset + 1; $p < $mlen; $p++ ) { $compare = substr( $arr[0], $offset, $p - $offset ); $match = TRUE; foreach( $arr as $str ) { if ( substr( $str, $offset, $p - $offset ) != $compare ) { $match = FALSE; } } if ( $match ) { $common = $compare; } } return $common; } $codes = array( 'ABC 123', 'ABC 124', 'ABC 145', ); echo findcommon( $codes ); // result: "ABC 1" $codes2 = array( 'ABC 1', 'ABC 123', 'ABC 456', ); echo findcommon( $codes2 ); // result: "ABC " $codes3 = array( 'ABC 123', 'ABC 124', ); echo findcommon( $codes3, 1 ); // result: "BC 12" $codes4 = array( 'ABC 123', 'AB3 ABC', ); echo findcommon( $codes4, 2 ); // result: false ?>

« previous php.notes (#107572) next »