note 107111 added to function.preg-match

From: Date: Sun, 08 Jan 2012 14:11:33 +0000
Subject: note 107111 added to function.preg-match
Groups: php.notes 
Request: Send a blank email to php-notes+get-185457@lists.php.net to get a copy of this message
here is a little function to get an associative array instead of the numeric one. <?php function preg_match_assoc($pattern, $subject, $assoc, $flags = 0, $offset = 0) { $matches = array(); eval('preg_match($pattern, $subject, $matches, $flags, $offset);'); $n = 0; foreach($matches as $result) { $array[$assoc[$n]] = $result; $n++; } return $array; } ?> example of use <?php $assocs = array( 'all', 'a-1', 'i-1', 'a-2', 'ia-1', 'ia-2' ); $test = preg_match_assoc('#([a-z]+)([0-9]+)([a-z]+)\-([a-z|0-9]+)\-([a-z|0-9]+)#', 'az45rt-df36qz-fg89ih', $assocs); // $test will contain : // // array // 'all' => string 'az45rt-df36qz-fg89ih' (length=20) // 'a-1' => string 'az' (length=2) // 'i-1' => string '45' (length=2) // 'a-2' => string 'rt' (length=2) // 'ia-1' => string 'df36qz' (length=6) // // Instead of : // // array // 0 => string 'az45rt-df36qz-fg89ih' (length=20) // 1 => string 'az' (length=2) // 2 => string '45' (length=2) // 2 => string 'rt' (length=2) // 4 => string 'df36qz' (length=6) // 5 => string 'fg89ih' (length=6) ?> ---- Server IP: 69.147.83.197 Probable Submitter: 93.23.23.43 ---- Manual Page -- http://www.php.net/manual/en/function.preg-match.php Edit -- https://master.php.net/note/edit/107111 Del: integrated -- https://master.php.net/note/delete/107111/integrated Del: useless -- https://master.php.net/note/delete/107111/useless Del: bad code -- https://master.php.net/note/delete/107111/bad+code Del: spam -- https://master.php.net/note/delete/107111/spam Del: non-english -- https://master.php.net/note/delete/107111/non-english Del: in docs -- https://master.php.net/note/delete/107111/in+docs Del: other reasons-- https://master.php.net/note/delete/107111 Reject -- https://master.php.net/note/reject/107111 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#185457) next »