note 83944 added to function.preg-match-all

From: Date: Thu, 19 Jun 2008 20:46:28 +0000
Subject: note 83944 added to function.preg-match-all
Groups: php.notes 
Request: Send a blank email to php-notes+get-140597@lists.php.net to get a copy of this message
Perhaps you want to find the positions of all anchor tags. This will return a two dimensional array of which the starting and ending positions will be returned. <?php function getTagPositions($strBody) { define(DEBUG, false); define(DEBUG_FILE_PREFIX, "/tmp/findlinks_"); preg_match_all("/<[^>]+>(.*)<\/[^>]+>/U", $strBody, $strTag, PREG_PATTERN_ORDER); $intOffset = 0; $intIndex = 0; $intTagPositions = array(); foreach($strTag[0] as $strFullTag) { if(DEBUG == true) { $fhDebug = fopen(DEBUG_FILE_PREFIX.time(), "a"); fwrite($fhDebug, $fulltag."\n"); fwrite($fhDebug, "Starting position: ".strpos($strBody, $strFullTag, $intOffset)."\n"); fwrite($fhDebug, "Ending position: ".(strpos($strBody, $strFullTag, $intOffset) + strlen($strFullTag))."\n"); fwrite($fhDebug, "Length: ".strlen($strFullTag)."\n\n"); fclose($fhDebug); } $intTagPositions[$intIndex] = array('start' => (strpos($strBody, $strFullTag, $intOffset)), 'end' => (strpos($strBody, $strFullTag, $intOffset) + strlen($strFullTag))); $intOffset += strlen($strFullTag); $intIndex++; } return $intTagPositions; } $strBody = 'I have lots of <a href="http://my.site.com">links</a> on this <a href="http://my.site.com">page</a> that I want to <a href="http://my.site.com">find</a> the positions.'; $strBody = strip_tags(html_entity_decode($strBody), '<a>'); $intTagPositions = getTagPositions($strBody); print_r($intTagPositions); /***** Output: Array ( [0] => Array ( [start] => 15 [end] => 53 ) [1] => Array ( [start] => 62 [end] => 99 ) [2] => Array ( [start] => 115 [end] => 152 ) ) *****/ ?> ---- Server IP: 69.147.83.197 Probable Submitter: 168.28.201.147 ---- Manual Page -- http://www.php.net/manual/en/function.preg-match-all.php Edit -- https://master.php.net/note/edit/83944 Del: integrated -- https://master.php.net/note/delete/83944/integrated Del: useless -- https://master.php.net/note/delete/83944/useless Del: bad code -- https://master.php.net/note/delete/83944/bad+code Del: spam -- https://master.php.net/note/delete/83944/spam Del: non-english -- https://master.php.net/note/delete/83944/non-english Del: in docs -- https://master.php.net/note/delete/83944/in+docs Del: other reasons-- https://master.php.net/note/delete/83944 Reject -- https://master.php.net/note/reject/83944 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#140597) next »